Project 2 - Measuring distance of an object using ultrasonic sensor (HC-SR04)
// Define the pins for the ultrasonic sensor
const int trigPin = 9;
const int echoPin = 10;
// Variables to store the distance measurement
long duration;
int distance;
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Set trigPin as output and echoPin as input
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
// Clear the trigPin before sending the pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Send a 10 microsecond pulse to trigger the sensor
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of the pulse on the echoPin
duration = pulseIn(echoPin, HIGH);
// Calculate the distance based on the speed of sound (343m/s)
// and the duration of the pulse
distance = duration * 0.0343 / 2; // Divide by 2 as the sound travels round trip
// Print the distance to the serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Delay before taking the next measurement
delay(1000);
}