const int TRIGGER_PIN = 4; // Trigger pin of the ultrasonic sensor
const int ECHO_PIN = 13; // Echo pin of the ultrasonic sensor
void setup() {
pinMode(TRIGGER_PIN, OUTPUT); // Set trigger pin as an output
pinMode(ECHO_PIN, INPUT); // Set echo pin as an input
Serial.begin(9600); // Initialize serial communication
}
void loop() {
// Generate a 10us pulse on the trigger pin to start the ultrasonic signal
digitalWrite(TRIGGER_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGGER_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN, LOW);
// Measure the duration of the echo signal
long duration = pulseIn(ECHO_PIN, HIGH);
// Calculate the distance in cm
float distance = duration * 0.034 / 2;
// Print the distance to the serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Wait for 500ms before sending the next ultrasonic signal
delay(500);
}