#define TRIG_PIN 6
#define ECHO_PIN 7
unsigned long duration, distance;
int send_time = 500;
unsigned long befor_time = 0;
String last_data = "S";
void setup() {
pinMode(ECHO_PIN, INPUT);
pinMode(TRIG_PIN, OUTPUT);
Serial.begin(115200);
befor_time = millis();
}
void loop() {
unsigned long now = millis();
if( now - befor_time >= send_time ){
befor_time = now;
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
duration = pulseIn(ECHO_PIN, HIGH);
distance = ((float)(340 * duration)/1000)/2;
String state;
if( distance >= 2000 ){ // Safety
state = 'S';
}else if(distance < 2000 && distance > 1000 ){ // Warning
state = 'W';
}else{ // Dangerous
state = 'D';
}
if( state != last_data ){
last_data = state;
Serial.print( state + "\n");
}else{
Serial.print("DISTANCE\r" + String(distance) + "\n");
}
}
}
★ [ IOT코아 ]에서 실행방법은 아래 링크를 참고하세요
https://koa-rea.tistory.com/52
두개의 아두이노 보드 연동하기
★ 본 예제 대상 코드는 아래 링크를 참고해주세요 https://koa-rea.tistory.com/51 아두이노 초음파거리센서 코드( 연동 ) #define TRIG_PIN 6 #define ECHO_PIN 7 unsigned long duration, distance; int send_time = 500; unsigned lon
koa-rea.tistory.com
'아두이노 예제 코드' 카테고리의 다른 글
아두이노 IOT 출입시스템 만들기( 코드 ) (0) | 2022.12.01 |
---|---|
아두이노 MLX90614, DHT11 코드 (0) | 2022.11.30 |
아두이노 32x8 매트릭스 코드( 연동 ) (2) | 2022.11.30 |
아두이노 초음파거리센서 코드 (0) | 2022.11.29 |
아두이노 LED ON/OFF 자동모드(코드) (0) | 2022.11.29 |
댓글