Distance: Out of range or error
00:36:25.521 -> Distance: Out of range or error
00:36:25.630 -> Distance: Out of range or error
00:36:25.763 -> Distance: Out of range or error
00:36:25.874 -> Distance: Out of range or error
00:36:26.014 -> Distance: Out of range or error
00:36:26.163 -> Distance: Out of range or error
00:36:26.280 -> Distance: Out of range or error
#define TRIG_PIN 8 // TRIG on pin 8
#define ECHO_PIN 7 // ECHO on pin 7
void setup() {
Serial.begin(115200); // Start serial communication
pinMode(TRIG_PIN, OUTPUT); // Set TRIG as OUTPUT
pinMode(ECHO_PIN, INPUT); // Set ECHO as INPUT
}
void loop() {
// Clear the TRIG pin
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2); // Wait for 2 microseconds
// Trigger the sensor by sending a HIGH pulse for 10 microseconds
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10); // Wait for 10 microseconds
digitalWrite(TRIG_PIN, LOW);
// Measure the time it takes for the pulse to return to the ECHO pin
long duration = pulseIn(ECHO_PIN, HIGH); // Measure pulse duration in microseconds
// Calculate the distance in cm (speed of sound = 343 m/s, 1 cm = 29 microseconds)
long distance = duration / 58.2;
// Print the distance if it's valid, else print error message
Serial.print("Distance: ");
if (distance > 0 && distance < 400) {
Serial.print(distance);
Serial.println(" cm");
} else {
Serial.println("Out of range or error");
}
delay(500); // Wait before taking another reading
}
