// Define the pins connected to the HC-SR04 sensor
const int trigPin = 27; // Trigger pin connected to Arduino digital pin 9
const int echoPin = 26; // Echo pin connected to Arduino digital pin 10
// Define variables for duration and distance
long duration; // Variable to store the duration of the sound wave travel
int distanceCm; // Variable to store the calculated distance in centimeters
void setup() {
// Initialize serial communication at 9600 baud rate
Serial.begin(9600);
// Set the trigger pin as an output
pinMode(trigPin, OUTPUT);
// Set the echo pin as an input
pinMode(echoPin, INPUT);
}
void loop() {
// Clear the trigger pin by setting it low for a short period
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Set the trigger pin high for 10 microseconds to send out a pulse
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of the pulse on the echo pin
duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters
// Speed of sound is approximately 0.034 cm/microsecond.
// We divide by 2 because the sound travels to the object and back.
distanceCm = duration * 0.0341 / 2;
// Print the distance to the Serial Monitor
Serial.print("Distance: ");
Serial.print(distanceCm);
Serial.println(" cm");
// Add a small delay between measurements
delay(1000);
}