#define PIN_TRIG 5 // Trigger Pin (Change to GPIO 5)
#define PIN_ECHO 18 // Echo Pin (Change to GPIO 18)
void setup() {
Serial.begin(115200);
pinMode(PIN_TRIG, OUTPUT);
pinMode(PIN_ECHO, INPUT);
}
void loop() {
// Start a new measurement
digitalWrite(PIN_TRIG, LOW);
delayMicroseconds(2);
digitalWrite(PIN_TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(PIN_TRIG, LOW);
// Read the Echo pulse duration
long duration = pulseIn(PIN_ECHO, HIGH, 30000); // Timeout after 30ms
if (duration == 0) {
Serial.println("Error: No echo received");
} else {
float distance_cm = duration * 0.0343 / 2;
float distance_in = distance_cm / 2.54;
Serial.print("Distance in CM: ");
Serial.println(distance_cm);
Serial.print("Distance in inches: ");
Serial.println(distance_in);
}
delay(2000); // Delay 1 second for next measurement
}