Challenge

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

To achieve the goals of measuring the distance of an object using an Ultrasonic Distance Sensor (28015 Ping) and smoothening the sensor data using a moving average filter, you can follow these steps:

Hardware Setup:
1. Connect the VCC pin of the Ultrasonic Distance Sensor to the 5V pin of the Arduino.
2. Connect the GND pin of the Ultrasonic Distance Sensor to the GND pin of the Arduino.
3. Connect the TRIG pin of the Ultrasonic Distance Sensor to a digital pin of the Arduino (e.g., pin 2).
4. Connect the ECHO pin of the Ultrasonic Distance Sensor to another digital pin of the Arduino (e.g., pin 3).

Software Setup:
5. Open the Arduino IDE and create a new sketch.
6. Define the pin assignments for TRIG and ECHO:
```cpp
const int trigPin = 2;
const int echoPin = 3;
```
7. Define variables for distance measurement and moving average filtering:
```cpp
const int numReadings = 10; // Number of readings for moving average
int readings[numReadings]; // Array to store readings
int index = 0; // Current index in the array
long total = 0; // Sum of readings
int averageDistance = 0; // Average distance
```
8. In the `setup()` function, initialize the serial communication and set the TRIG pin as OUTPUT and the ECHO pin as INPUT:
```cpp
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
```
9. Create a function to calculate the moving average distance:
```cpp
int calculateMovingAverage() {
total -= readings[index];
readings[index] = pulseIn(echoPin, HIGH) / 74 / 2; // Convert time to distance in inches
total += readings[index];
index = (index + 1) % numReadings;
return total / numReadings;
}
```
10. In the `loop()` function, trigger the Ultrasonic Distance Sensor and calculate the moving average distance:
```cpp
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

averageDistance = calculateMovingAverage();

Serial.print("Distance: ");
Serial.print(averageDistance);
Serial.println(" inches");

delay(500); // Adjust the delay as needed
}
```
11. Upload the code to the Arduino board.

Testing:
12. Provide power to the Arduino board.
13. Open the serial monitor in the Arduino IDE to view the measured distance in inches.
14. The Ultrasonic Distance Sensor will continuously measure the distance of the object and display the average distance after applying the moving average filter.
15. Observe the smoothened sensor data, which eliminates high-frequency variations, resulting in a more stable distance measurement.

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.