Challenge

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

CODE:

CODE:

const int samples = 5; // Number of measurements to take and average
int data[samples]; // Array to store the measurements
int index = 0; // Index to keep track of the current measurement
int total = 0; // Running total of all measurements
int average = 0; // Calculated average distance
int duration = 0; // Duration of the pulse
int inch = 0; // Distance in inch
const int inputPin = 4; // Pin connected to the ultrasonic sensor

void setup() {
Serial.begin(9600); // Start serial communication
for (int i = 0; i < samples; i++) {
data[i] = 0; // Initialize all elements in the data array to 0
}
}

void loop() {
total = total - data[index]; // Subtract the oldest measurement from the total

pinMode(inputPin, OUTPUT); // Set the pin to output
digitalWrite(inputPin, LOW); // Send a low signal to trigger the sensor
delayMicroseconds(2); // Wait for 2 microseconds
digitalWrite(inputPin, HIGH); // Send a high signal
delayMicroseconds(10); // Wait for 10 microseconds
digitalWrite(inputPin, LOW); // Send a low signal to end the pulse

pinMode(inputPin, INPUT); // Set the pin to input
duration = pulseIn(inputPin, HIGH); // Measure the duration of the pulse

inch = (0.01723 * duration) / 2.54; // Calculate the distance in inch
data[index] = inch; // Store the measurement in the data array

total = total + data[index]; // Add the newest measurement to the total

index = index + 1; // Increment the index

if (index >= samples) {
index = 0; // Reset the index if all samples have been taken
}

average = total / samples; // Calculate the average distance
Serial.print("Object is ");
Serial.print(average); // Print the average distance
Serial.println("inches away!");
delay(100); // Wait for 100 milliseconds before taking another measurement
}

Output:

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.