int echo = 4; // GPIO 4 (D2) connected to the echo pin of the ultrasonic sensor
int trigger = 5; // GPIO 5 (D1) connected to the trigger pin of the ultrasonic sensor
long traveltime; // Variable to store the time duration
float distance; // Variable to store the calculated distance
void setup() {
pinMode(trigger, OUTPUT); // Declare trigger pin as output
pinMode(echo, INPUT); // Declare echo pin as input
Serial.begin(9600); // Start the serial communication at 9600 baud rate
}
void loop() {
// Trigger the ultrasonic sensor
digitalWrite(trigger, LOW);
delayMicroseconds(2); // Delay of 2 microseconds
digitalWrite(trigger, HIGH);
delayMicroseconds(10); // Send a 10-microsecond pulse
digitalWrite(trigger, LOW);
// Measure the time for the echo
traveltime = pulseIn(echo, HIGH);
// Calculate the distance
distance = traveltime * 0.034 / 2; // Convert time to distance (cm)
// Print the distance on the serial monitor
Serial.print("Distance = ");
Serial.print(distance);
Serial.println(" cm");
delay(100); // Wait for 100ms before the next measurement
}