Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
Description:
The code is an Arduino-based implementation for measuring the distance of an object using an Ultrasonic Distance Sensor (28015 Ping) and applying a Moving Average Filter to smoothen the sensor data. The main goal of the code is to obtain accurate and stable distance measurements by eliminating high-frequency variations present in the raw sensor readings.
The code begins by initializing the required variables and constants, including the trigger and echo pins of the Ultrasonic sensor, the number of readings to use in the moving average filter, and arrays to store the sensor readings. It also defines functions for reading the Ultrasonic sensor and calculating the moving average.
The readUltrasonicDistance function sends a trigger pulse to the sensor, measures the time taken for the echo to return, and calculates the distance in centimeters and inches. It then updates the readings array with the latest distance value and moves the read index for the moving average filter.
The calculateMovingAverage function updates the total sum of the readings and recalculates the average based on the new reading. It ensures that the moving average is continuously updated as new readings are obtained, effectively smoothening the data.
In the loop function, the code initially collects a specified number of readings to fill the readings array before starting the moving average process. Once enough initial readings are collected, the isReady flag is set to true, and the code enters the main loop for distance measurement. For each iteration, the code reads the Ultrasonic sensor, calculates the distance in inches and centimeters, and applies the moving average filter to obtain a smoothened distance value.
The code then prints the raw distance and the smoothened distance to the Serial Monitor, separated by tabs for better alignment and readability. The delay function ensures a short interval between consecutive measurements to avoid excessive readings.
Overall, the code showcases a practical application of an Ultrasonic Distance Sensor in distance measurement and demonstrates the effectiveness of a Moving Average Filter in producing more reliable and stable distance readings. It provides a valuable learning opportunity for students interested in sensor interfacing, data filtering, and accurate distance measurement using Arduino.
Tinkercad Link:
https://www.tinkercad.com/things/lCu0xDczhiq-fantabulous-lappi-crift/editel?sharecode=Co6ap_seblLizZGxX7XaT-GNkX80cS2WHTwma-IlBZ8
Connection:

Screenshot of Output:
* When distance is 40.8 inches

* When distance is 15 inches

Code:
const int triggerPin = 7; // Pin to trigger the Ultrasonic sensor
const int echoPin = 7; // Pin to receive the echo from the Ultrasonic sensor
const int numReadings = 10; // Number of readings for moving average filter
float readings[numReadings]; // Array to store sensor readings
int readIndex = 0; // Current position in the array
float total = 0.0; // Total of all readings
float smoothedDistance = 0.0; // Smoothed distance value
bool isReady = false; // Flag to indicate if enough initial readings have been collected
void setup() {
Serial.begin(9600); // Initialize Serial communication
}
// Function to read distance using Ultrasonic sensor
long readUltrasonicDistance(int triggerPin, int echoPin) {
pinMode(triggerPin, OUTPUT);
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
pinMode(echoPin, INPUT);
return pulseIn(echoPin, HIGH);
}
// Function to calculate moving average
float calculateMovingAverage(float distance) {
total = total - readings[readIndex]; // Remove the oldest reading from the total
readings[readIndex] = distance; // Store the latest reading in the array
total = total + readings[readIndex]; // Add the latest reading to the total
readIndex = (readIndex + 1) % numReadings; // Move to the next position in the array
return total / numReadings; // Calculate the average
}
void loop() {
if (!isReady) {
// Collect initial readings to fill the array
long duration = readUltrasonicDistance(triggerPin, echoPin);
float cm = duration * 0.01723;
float inches = cm / 2.54;
readings[readIndex] = inches;
total += readings[readIndex];
readIndex = (readIndex + 1) % numReadings;
// Check if we have enough initial readings
if (readIndex == 0) {
isReady = true;
Serial.println("System Ready! Starting measurements...");
}
delay(100);
} else {
// Start measuring and apply moving average filter
long duration = readUltrasonicDistance(triggerPin, echoPin);
float cm = duration * 0.01723;
float inches = cm / 2.54;
smoothedDistance = calculateMovingAverage(inches);
// Print the results to the Serial Monitor
Serial.print("Raw Distance: ");
Serial.print(inches, 2); // Print with 2 decimal places for precision
Serial.print(" inches");
Serial.print("\t\t"); // Add some tabs for alignment
Serial.print("Smoothened Distance: ");
Serial.print(smoothedDistance, 2); // Print with 2 decimal places for precision
Serial.println(" inches");
delay(1000);
}
}