#define TRIGGER_PIN 17
#define ECHO_PIN 16
void setup() {
Serial.begin(115200); // Start serial communication at 115200 baud
pinMode(TRIGGER_PIN, OUTPUT); // Set the trigger pin as an OUTPUT
pinMode(ECHO_PIN, INPUT); // Set the echo pin as an INPUT
}
void loop() {
long duration;
float distance;
// Send a 10 microsecond pulse to the trigger pin
digitalWrite(TRIGGER_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGGER_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN, LOW);
// Read the duration of the pulse from the echo pin
duration = pulseIn(ECHO_PIN, HIGH);
// Calculate the distance in cm (duration / 2) / 29.1
distance = (duration / 2.0) / 29.1;
// Print the distance to the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(500); // Wait for 500 milliseconds before taking the next reading
}