Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the
Code : Cpp
const int triggerPin = 3; // Connect trigger pin of the sensor to D3 on Arduino
const int echoPin = 2; // Connect echo pin of the sensor to D2 on Arduino
const int numReadings = 5; // Number of readings to average
unsigned long readings[numReadings]; // Store sensor readings
int readingsIndex = 0; // Index for the readings array
unsigned long total = 0; // Total of readings
int smoothedDistance = 0; // Smoothed distance value
void setup() {
Serial.begin(9600);
pinMode(triggerPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
unsigned long duration, inches;
// Trigger the sensor
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
// Measure the echo
duration = pulseIn(echoPin, HIGH);
// Calculate distance in inches
inches = microsecondsToInches(duration);
// Store the reading in the array
total -= readings[readingsIndex];
readings[readingsIndex] = inches;
total += inches;
readingsIndex = (readingsIndex + 1) % numReadings;
// Calculate the moving average
smoothedDistance = total / numReadings;
// Display the smoothed distance
Serial.print("Smoothed Distance: ");
Serial.print(smoothedDistance);
Serial.println(" inches");
delay(500); // Delay for half a second
}
unsigned long microsecondsToInches(unsigned long microseconds) {
// Conversion factor for microseconds to inches
return microseconds / 74 / 2;
}