Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
const int pingPin = 7; // Pin connected to the SIG pin of the sensor
const int numReadings = 10; // Number of readings for the moving average filter
long readings[numReadings]; // Array to store the sensor readings
int readIndex = 0; // Index of the current reading
long total = 0; // Sum of the readings
long average = 0; // Average of the readings
void setup() {
Serial.begin(9600); // Initialize serial communication
for (int i = 0; i < numReadings; i++) {
readings[i] = 0; // Initialize all readings to 0
}
}
void loop() {
// Establish variables for duration of the ping, and the distance result in inches and centimeters:
long duration, distance;
// The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
// The same pin is used to read the signal from the PING))): a HIGH pulse whose duration is the time (in microseconds) from the sending of the ping to the reception of its echo off an object.
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);
// Convert the time into a distance
distance = duration / 29 / 2; // Distance in cm
// Update the moving average
total = total - readings[readIndex]; // Subtract the last reading
readings[readIndex] = distance; // Store the new reading
total = total + readings[readIndex]; // Add the new reading to the total
readIndex = (readIndex + 1) % numReadings; // Advance to the next position in the array
average = total / numReadings; // Calculate the average
// Print the average distance
Serial.print("Distance (cm): ");
Serial.println(average);
delay(100); // Wait a bit before the next loop
}