Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
#define trigPin 7
#define echoPin 6
const int numReadings = 10; // Number of readings for moving average filter
int readings[numReadings]; // Array to store sensor readings
int index = 0; // Index for the readings array
long total = 0; // Variable to store the sum of sensor readings
void setup()
{
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop()
{
long distance = getDistance(); // Measure distance using ultrasonic sensor
long smoothedDistance = getMovingAverage(distance); // Apply moving average filter
Serial.print("Raw Distance: ");
Serial.print(distance);
Serial.print(" inches, Smoothed Distance: ");
Serial.println(smoothedDistance);
delay(100);
}
long getDistance()
{
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH);
return duration / 74 / 2;
}
long getMovingAverage(long newReading)
{
total -= readings[index]; // Subtract the oldest reading
readings[index] = newReading; // Store the new reading
total += readings[index]; // Add the new reading
index = (index + 1) % numReadings; // Move to the next position in the array
long average = total / numReadings; // Calculate the moving average
return average;
}