Challenge

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 sensor data using moving average filter

Code:

// pin that the ultrasonic sensor is connected to
const int Ultra_Signal_Pin = 7;
//Number of readings that will be used to calculate the moving average
const int numReadings = 10;

// Array to store sensor readings
long readings[numReadings];
//Keeps track of the current index in the readings array
int currentIndex = 0;

void setup()
{
//Initialize the serial port
Serial.begin(9600);
}

//This function continuously measures the distance to the object and calculates the moving average
void loop()
{
//The duration variable is set to the duration of the ultrasonic pulse &
//The cm variable is used to convert the duration variable to centimeters
long duration, cm;

//Ultrasonic Distance Measurement
//sets the Ultra_Signal_Pin pin as an output pin
pinMode(Ultra_Signal_Pin, OUTPUT);
//sets the Ultra_Signal_Pin pin to LOW
digitalWrite(Ultra_Signal_Pin, LOW);
//waits for 2 microseconds
delayMicroseconds(2);
//sets the Ultra_Signal_Pin pin to HIGH
digitalWrite(Ultra_Signal_Pin, HIGH);
//waits for 10 microseconds
delayMicroseconds(10);
//sets the Ultra_Signal_Pin pin to LOW
digitalWrite(Ultra_Signal_Pin, LOW);

//Ultra_Signal_Pin as an input pin and use the pulseIn() function to measure the duration of the echo pulse received from the ultrasonic sensor
pinMode(Ultra_Signal_Pin, INPUT);
duration = pulseIn(Ultra_Signal_Pin, HIGH);

//converts the duration of the pulse to centimeters
cm = microsecondsToCentimeters(duration);

//stores the latest measurement in the readings array
readings[currentIndex] = cm;

//Increments the currentIndex variable and wraps it around if necessary
currentIndex = (currentIndex + 1) % numReadings;

//The total variable is used to store the sum of the sensor readings
long total = 0;

for(int i = 0; i < numReadings; i++)
{
total += readings[i];
}
//The moving average is calculated by dividing the total variable by the numReadings variable.
long movingAverage = total / numReadings;

// Print the smoothed distance
Serial.print("Smoothed Distance: ");
Serial.print(movingAverage);
Serial.println(" cm");

delay(100); // Wait for a short interval before next measurement
}

//declaring the function and takes a long variable as an argument.
longmicrosecondsToCentimeters(longmicroseconds)
{
// Speed of sound = 343 meters per second = 34300 cm/s
// Distance traveled = speed * time
// Divide by 2 because the sound wave travels to the object and back
return microseconds / 29 / 2;
}

Overview of the Project:

This project is an implementation of an ultrasonic distance measurement system using an Arduino board. It utilizes an ultrasonic sensor to measure the distance to an object and calculates a moving average of the measured values to provide a smoother and more reliable reading.

The project consists of hardware components, including an Arduino board and an ultrasonic sensor, as well as the corresponding software code that runs on the Arduino. The ultrasonic sensor emits ultrasonic waves and measures the time it takes for the waves to bounce back after hitting an object. Based on this time measurement, the distance to the object can be calculated.

1. Hardware Setup:
- Connect the ultrasonic sensor to the Arduino board.
- The ultrasonic sensor typically has two pins: one for triggering the ultrasonic pulse and one for receiving the echo pulse.
- Connect the trigger pin of the sensor to a digital pin on the Arduino (in this code, pin 7 is used), and connect the echo pin to another digital pin.

2. Software Implementation:
- The code begins by declaring constants and variables. `Ultra_Signal_Pin` represents the Arduino pin number to which the ultrasonic sensor's trigger pin is connected, and `numReadings` determines the number of readings used to calculate the moving average.
- An array called `readings` is declared to store the sensor readings, and `currentIndex` keeps track of the current index in the `readings` array.

3. `setup()` Function:
- The `setup()` function is called once when the Arduino board powers up or is reset.
- In this code, it initializes the serial port with a baud rate of 9600, enabling communication with the computer via the USB cable.

4. `loop()` Function:
- The `loop()` function is executed continuously after the `setup()` function.
- It performs the following steps in a loop:
- Declares variables `duration` and `cm` to store the duration of the ultrasonic pulse and the calculated distance in centimeters, respectively.
- Sends a trigger signal to the ultrasonic sensor to start the measurement process.
- Measures the duration of the echo pulse using the `pulseIn()` function, which waits for the echo pulse and returns the pulse duration in microseconds.
- Converts the pulse duration to centimeters using the `microsecondsToCentimeters()` function, which calculates the distance based on the speed of sound.
- Stores the latest measurement in the `readings` array at the current index.
- Updates the `currentIndex` variable to point to the next position in the `readings` array, wrapping around to the beginning if necessary.
- Calculates the moving average of the stored readings by summing them up and dividing by the `numReadings`.
- Prints the smoothed distance (moving average) to the serial monitor for observation.
- Adds a short delay of 100 milliseconds before the next measurement to avoid continuous and rapid measurements.

5. `microsecondsToCentimeters()` Function:
- This function takes the duration of the pulse in microseconds as an argument and calculates the distance in centimeters based on the speed of sound.
- It uses a conversion factor of 29 (based on the speed of sound) and divides the duration by 2 because the sound wave travels to the object and back.

Overall, this project enables you to measure distances using an ultrasonic sensor and an Arduino board. The moving average calculation helps to smooth out the readings and provide a more accurate representation of the distance to the object. The measurements are displayed on the serial monitor, allowing you to monitor the distance changes in real-time.

Goals:

1. Measure distance: The primary goal of this project is to accurately measure the distance between the ultrasonic sensor and an object using the echo pulse duration.

2. Smooth distance readings: To provide more stable and reliable distance measurements, the project aims to calculate a moving average of multiple readings, reducing the impact of outliers or temporary fluctuations.

3. Real-time monitoring: The project intends to continuously update and display the distance readings in real-time, allowing users to monitor changes in object proximity.

4. Precise measurements: By converting the echo pulse duration into centimeters using the speed of sound, the project aims to provide reasonably accurate distance measurements for various applications.

5. Automation integration: The project can be integrated into automation systems, such as robotics or home automation, where knowing the distance to an object is crucial for decision-making and controlling actions.

6. Versatility: The project seeks to provide a flexible solution that can be easily customized and adapted to different scenarios and environments where distance measurements are required.

Key Highlights of the Project:

1. Ultrasonic Distance Measurement: The project utilizes an ultrasonic sensor to accurately measure the distance to an object based on the time it takes for the ultrasonic pulse to travel to the object and back.

2. Moving Average Calculation: To provide a smoother and more stable distance reading, the code implements a moving average calculation by storing multiple readings in an array and averaging them over time.

3. Circular Buffer: The project uses a circular buffer approach to store the sensor readings, ensuring that the most recent readings replace the oldest ones in a continuous loop.

4. Serial Communication: The Arduino board communicates with a computer through the serial port, allowing the distance measurements to be displayed on the serial monitor for real-time observation and analysis.

5. Conversion to Centimeters: The duration of the ultrasonic pulse is converted to centimeters using a simple calculation based on the speed of sound, providing distance readings in a more intuitive unit.

6. Versatile Applications: This project's functionality can be applied in various domains such as robotics, home automation, security systems, and any scenario that requires proximity sensing or distance measurements.

Deliverables of this project:

1. Arduino code: The deliverable for this project includes the Arduino code that interfaces with the ultrasonic sensor, measures the distance, and calculates the moving average. The code should be well-documented and easy to understand.

2. Circuit diagram: A circuit diagram illustrating the connection between the Arduino board and the ultrasonic sensor should be provided. This diagram helps in replicating the project and ensures correct wiring.

3. Working prototype: A physical prototype demonstrating the functionality of the project should be built. It should include the Arduino board, the ultrasonic sensor, and any other necessary components. The prototype should accurately measure distances and display the smoothed readings.

4. Documentation: A comprehensive documentation file should be prepared, explaining the project's purpose, components used, circuit diagram, code explanation, and any other relevant information. This documentation helps others understand and replicate the project.

5. Test results: The project should undergo thorough testing to validate its accuracy and reliability. Test results, including measurements at different distances, should be documented to showcase the performance of the ultrasonic distance measurement system.

6. Presentation or demonstration: A presentation or demonstration of the project can be included as a deliverable. This allows for showcasing the project's features, explaining its functionality, and answering any questions. It can be in the form of a video, slides, or a live presentation.

Expected Outcomes:

1. Distance Measurement: The ultrasonic sensor will measure the distance between the sensor and an object in front of it. The measured distance will be in centimeters.

2. Moving Average: The project calculates a moving average of the measured distances. The moving average provides a smoother and more stable reading by considering a specified number of previous readings. In this case, the number of readings used to calculate the moving average is defined by the `numReadings` variable.

3. Smoothing: By calculating the moving average, the project reduces the impact of any sudden variations or noise in the measured distances. It provides a more reliable and consistent distance reading by taking into account multiple readings over time.

4. Serial Output: The smoothed distance will be displayed on the serial monitor. The Arduino board will communicate with the computer, and the distance value will be printed as "Smoothed Distance: [distance] cm" continuously. The serial monitor allows for real-time observation and analysis of the distance measurements.

5. Continuous Operation: The code is structured to continuously measure and update the distance reading. The `loop()` function ensures that the ultrasonic sensor is triggered, and the distance is calculated repeatedly with a short delay between measurements. This allows for continuous monitoring of the distance to the object.

6. Sensitivity: The project is sensitive to the presence of objects in front of the ultrasonic sensor. It can detect the distance to objects within its range, typically several meters. When an object is closer, the measured distance will decrease, and vice versa.

7. Real-Time Feedback: With the continuous distance measurements and moving average calculation, the project can provide real-time feedback about the changes in the distance to the object. This can be useful in various applications such as robotics, obstacle avoidance systems, or measuring the level of a liquid in a container.

8. Adjustable Parameters: The code allows for flexibility in adjusting the parameters according to specific requirements. The pin number to which the ultrasonic sensor is connected (`Ultra_Signal_Pin`) and the number of readings used for the moving average calculation (`numReadings`) can be modified to suit different setups and scenarios.

In summary, the expected outcome of this project is a continuous and smoothed distance measurement between an ultrasonic sensor and an object. The moving average provides a stable reading, and the serial output allows for real-time monitoring and analysis of the measured distances.

All the necessary screenshots are attached herewith

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.