Challenge

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

To measure the distance of an object using an ultrasonic distance sensor (such as the HC-SR04, which you mentioned as 28015 Ping) and smoothen the sensor data using a moving average filter, you can use the following Arduino code:

const int trigPin = 9; // Trigger pin of the ultrasonic sensor
const int echoPin = 10; // Echo pin of the ultrasonic sensor

const int numReadings = 10; // Number of readings for the moving average filter
int readings[numReadings]; // Array to store sensor readings
int index = 0; // Index of the current reading
int total = 0; // Total of all readings
int averageDistance = 0; // Average distance calculated

void setup() {
Serial.begin(9600); // Initialize serial communication
pinMode(trigPin, OUTPUT); // Set trigger pin as output
pinMode(echoPin, INPUT); // Set echo pin as input
}

void loop() {
// Trigger the ultrasonic sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

// Measure the duration of the pulse from the echo pin
long duration = pulseIn(echoPin, HIGH);

// Calculate the distance based on the speed of sound (340 m/s)
int distance = duration * 0.034 / 2;

// Smoothen the sensor data using a moving average filter
total = total - readings[index]; // Subtract the oldest reading
readings[index] = distance; // Store the new reading
total = total + readings[index]; // Add the new reading
index = (index + 1) % numReadings; // Increment the index, reset if needed
averageDistance = total / numReadings; // Calculate the average distance

// Print the average distance to the serial monitor
Serial.print("Average Distance: ");
Serial.print(averageDistance);
Serial.println(" cm");

delay(100); // Delay between readings
}

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.