/**
HC-SR04 Distance Sensor Example
https://wokwi.com/arduino/projects/304444938977804866
*/
#define PIN_TRIG 3
#define PIN_ECHO 2
void setup() {
Serial.begin(115200);
pinMode(PIN_TRIG, OUTPUT);
pinMode(PIN_ECHO, INPUT);
}
void loop() {
// Start a new measurement:
digitalWrite(PIN_TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(PIN_TRIG, LOW);
// Read the result:
float duration = pulseIn(PIN_ECHO, HIGH);
Serial.print("Distance is: ");
Serial.print(duration / 58);
Serial.println(" cm");
Serial.print("Distance is: ");
Serial.print((duration / 58)/100);
Serial.println(" m");
if((duration / 58)/100 > 0.02 && (duration / 58)/100 <0.1){
Serial.println("Move away");
}
else if((duration / 58)/100 > 0.1 && (duration / 58)/100 < 0.3){
Serial.println("It's good");
}
else if((duration / 58)/100 > 0.3){
Serial.println("Too far");
}
delay(1000);
}