Challenge

Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter

const int trigPin = 3; // Trigger pin of ultrasonic sensor
const int echoPin = 2; // Echo pin of ultrasonic sensor
const int windowSize = 5; // Size of the moving average filter window
long duration; // Duration of sound wave travel time
int distance; // Calculated distance in cm
int readings[windowSize]; // Array to store sensor readings for moving average filter
int index = 0; // Index for readings array

void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}

void loop() {
// Send 10us pulse to trigger pin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delay(10);
digitalWrite(trigPin, LOW);

// Measure duration of echo pulse
duration = pulseIn(echoPin, HIGH);

// Calculate distance in cm
distance = duration / 58.2;

// Add distance reading to readings array
readings[index] = distance;

// Increment index and wrap around if necessary
index = (index + 1) % windowSize;

// Calculate moving average of readings array
int sum = 0;
for (int i = 0; i < windowSize; i++) {
sum += readings[i];
}
int filteredDistance = sum / windowSize;

// Print distance and filtered distance to serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.print(" cm, Filtered Distance: ");
Serial.print(filteredDistance);
Serial.println(" cm");

// Delay before next measurement
delay(100);
}

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.