Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
Components Needed:
- 1 Arduino board
- 1 Ultrasonic Distance Sensor (28015 Ping)
- Breadboard and jumper wires
Working Principle:
- The sensor emits a sound wave at a frequency above human hearing (ultrasonic) and measures the time it takes for the echo to return after bouncing off an object.
- The distance is calculated using the formula: Distance=2Time×Speed of Sound
- The factor of 2 accounts for the round trip of the sound wave (to the object and back).
Connections for the 28015 Ping Sensor:
- VCC to 5V on Arduino.
- GND to Ground on Arduino.
- SIG (Signal Pin) to any digital I/O pin (e.g., pin 7).
Moving Average Filter:
- The moving average filter smoothens the data by averaging a certain number of the most recent data points. This reduces the effect of outliers or sudden changes in the sensor readings.
Code:
// Define pin numbers
const int pingPin = 7; // Pin connected to the Ping sensor's SIG pin
// Parameters for Moving Average Filter
const int numReadings = 10;
int readings[numReadings]; // Array to hold sensor readings
int readIndex = 0; // Index for current reading
int total = 0; // Total of readings
int average = 0; // The average value
void setup() {
Serial.begin(9600); // Start serial communication
pinMode(pingPin, OUTPUT);
// Initialize all readings to 0
for (int i = 0; i < numReadings; i++) {
readings[i] = 0;
}
}
void loop() {
long duration, inches;
// Trigger the Ping sensor
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
// Read the echo
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);
// Convert time into distance in inches
inches = microsecondsToInches(duration);
// Update the moving average filter
total = total - readings[readIndex]; // Subtract the oldest reading
readings[readIndex] = inches; // Store the new reading
total = total + readings[readIndex]; // Add the new reading to the total
readIndex = (readIndex + 1) % numReadings;// Advance to the next position
average = total / numReadings; // Calculate the average
// Print the results to the Serial Monitor
Serial.print("Distance: ");
Serial.print(average);
Serial.println(" inches");
delay(100); // Delay for readability and stability
}
// Convert the duration to distance in inches
long microsecondsToInches(long microseconds) {
return microseconds / 74 / 2;
}