#define TRIG_PIN 12 // Trigger pin
#define ECHO_PIN 13 // Echo pin
void setup() {
Serial.begin(9600); // Initialize serial communication
pinMode(TRIG_PIN, OUTPUT); // Set the trigger pin as an output
pinMode(ECHO_PIN, INPUT); // Set the echo pin as an input
}
void loop() {
float averageDistance = measureAverageDistance(10); // Take 10 measurements and calculate the average
// Print the average distance to the Serial Monitor
Serial.print("Average Distance: ");
Serial.print(averageDistance);
Serial.println(" cm");
delay(1000); // Delay before taking another set of measurements
}
float measureDistance() {
long duration;
float distance;
// Clear the trigger pin
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
// Send a 10µs pulse to trigger the sensor
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Measure the time of the echo pulse
duration = pulseIn(ECHO_PIN, HIGH);
// Calculate the distance (speed of sound is 34300 cm/s)
distance = (duration * 0.0343) / 2;
return distance;
}
float measureAverageDistance(int readings) {
float totalDistance = 0.0;
// Take multiple measurements
for (int i = 0; i < readings; i++) {
totalDistance += measureDistance(); // Add the distance from each measurement
delay(50); // Small delay between measurements for stability
}
// Calculate the average distance
return totalDistance / readings;
}