Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
Aim: The aim of this project is to measure the distance of an object using an ultrasonic sensor and apply a moving average filter to smoothen the sensor data. The moving average filter will help reduce noise and fluctuations in the distance measurements, providing a more stable and accurate result.
Objective: The objective is to create a system that utilizes an ultrasonic sensor to measure the distance of an object. The distance measurements will be processed using a moving average filter to eliminate noise and produce a smoother and more reliable distance reading.
Goals: Measuring the distance in terms of inches of an object using Ultrasonic Distance Sensor (28015 Ping). The sensor data is smoothened by using Moving average filter technique to eliminate the high frequency variations from the sensor data.
Key Highlights of the Project: Measuring the distance travelled by the wave to the object and gets bounced back from the object to sensor. Smoothening the sensor data by moving average filter technique, the filter has a window of certain size. That window determines that how many data the filter can take.
CODE:
#define TRIGGER_PIN 9
#define ECHO_PIN 10
#define NUM_SAMPLES 5
long duration;
int distance;
int samples[NUM_SAMPLES];
int sampleIndex = 0;
void setup() {
Serial.begin(9600);
pinMode(TRIGGER_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
}
void loop() {
// Trigger the ultrasonic sensor
digitalWrite(TRIGGER_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGGER_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN, LOW);
// Measure the duration of the echo pulse
duration = pulseIn(ECHO_PIN, HIGH);
// Calculate the distance in inches
distance = duration / 74 / 2;
// Apply moving average filter
samples[sampleIndex] = distance;
sampleIndex = (sampleIndex + 1) % NUM_SAMPLES;
int sum = 0;
for (int i = 0; i < NUM_SAMPLES; i++) {
sum += samples[i];
}
int smoothedDistance = sum / NUM_SAMPLES;
// Print the distance to the serial monitor
Serial.print("Distance: ");
Serial.print(smoothedDistance);
Serial.println(" inches");
delay(100);
}
Logic:
The code starts by defining constants for the trigger pin (TRIGGER_PIN), echo pin (ECHO_PIN), and the number of samples used in the moving average filter (NUM_SAMPLES).
In the setup() function, the serial communication is initialized, and the pin modes for the trigger and echo pins are set.
The loop() function runs continuously and performs the following steps:
The ultrasonic sensor is triggered by sending a 10-microsecond pulse on the trigger pin. This triggers the sensor to send out an ultrasonic wave.
The duration of the echo pulse is measured using the pulseIn() function. It waits for the echo pin to go high and then returns the duration in microseconds.
The distance is calculated by dividing the duration by the speed of sound (74 microseconds per inch) and dividing by 2 to account for the round-trip distance.
The distance value is stored in the distance variable.
The distance measurement is then passed through the moving average filter to smoothen the data.
The distance value is stored in an array of samples, and the sample index is incremented.
The sum of the samples is calculated, and the average distance is computed by dividing the sum by the number of samples.
The smoothed distance value is stored in the smoothedDistance variable.
The distance is printed to the serial monitor for display.
A delay of 100 milliseconds is added before the next iteration.
Comment:
To use this code, ensure that the ultrasonic distance sensor (28015 Ping) is connected to the correct trigger and echo pins on the Arduino board. By default, the code assumes that the trigger pin is connected to pin 9 and the echo pin is connected to pin 10.
Make sure to connect the VCC and GND pins of the ultrasonic sensor to the appropriate power and ground pins on the Arduino board. Additionally, connect the trigger pin of the sensor to the trigger pin specified in the code (TRIGGER_PIN) and the echo pin of the sensor to the echo pin specified in the code (ECHO_PIN).
If you have connected the ultrasonic sensor to different pins on the Arduino board, modify the TRIGGER_PIN and ECHO_PIN constants in the code to match your connections. For example, if you have connected the trigger pin of the sensor to pin 7 and the echo pin to pin 8, you would modify the code as follows:
#define TRIGGER_PIN 7
#define ECHO_PIN 8
After making the necessary changes, upload the code to your Arduino board and ensure that it is properly connected to the ultrasonic sensor. Open the serial monitor in the Arduino IDE at a baud rate of 9600 to view the distance readings. You should see the distance measurements displayed, which have been smoothened using the moving average filter.
It's important to double-check your hardware connections and ensure that they match the modifications you made in the code. Verify that the ultrasonic sensor is connected to the correct pins on the Arduino board according to the updated TRIGGER_PIN and ECHO_PIN values.
#define TRIGGER_PIN 9
#define ECHO_PIN 10
#define NUM_SAMPLES 5
long duration;
int distance;
int samples[NUM_SAMPLES];
int sampleIndex = 0;
void setup() {
Serial.begin(9600);
pinMode(TRIGGER_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
}
void loop() {
// Trigger the ultrasonic sensor
digitalWrite(TRIGGER_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGGER_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN, LOW);
// Measure the duration of the echo pulse
duration = pulseIn(ECHO_PIN, HIGH);
// Calculate the distance in centimeters
distance = duration * 0.034 / 2;
// Apply moving average filter
samples[sampleIndex] = distance;
sampleIndex = (sampleIndex + 1) % NUM_SAMPLES;
int sum = 0;
for (int i = 0; i < NUM_SAMPLES; i++) {
sum += samples[i];
}
int smoothedDistance = sum / NUM_SAMPLES;
// Print the distance to the serial monitor
Serial.print("Distance: ");
Serial.print(smoothedDistance);
Serial.println(" cm");
delay(100);
}
Explanation: The code provided demonstrates how to measure the distance of an object using an ultrasonic sensor and apply a moving average filter to smoothen the sensor data.
The TRIGGER_PIN and ECHO_PIN constants are defined to specify the pins connected to the ultrasonic sensor.
The NUM_SAMPLES constant is defined to specify the number of samples used in the moving average filter.
In the setup() function, the serial communication is initialized, and the pin modes for the trigger and echo pins are set.
The loop() function runs continuously and performs the following steps:
The ultrasonic sensor is triggered by sending a 10-microsecond pulse on the trigger pin.
The duration of the echo pulse is measured using the pulseIn() function, which waits for the echo pin to go high and then returns the duration in microseconds.
The distance is calculated by multiplying the duration by the speed of sound and dividing by 2, as the sound travels to the object and back.
The distance value is stored in the distance variable.
The distance measurement is then passed through the moving average filter to smoothen the data.
The distance value is stored in an array of samples, and the sample index is incremented.
The sum of the samples is calculated, and the average distance is computed by dividing the sum by the number of samples.
The smoothed distance value is stored in the smoothedDistance variable.
The distance is printed to the serial monitor for display.
A delay of 100 milliseconds is added before the next iteration.
Comment: To use this code, make sure you have connected the ultrasonic sensor to the correct pins on the Arduino board. In the code, the TRIGGER_PIN and ECHO_PIN constants are defined to specify the pins connected to the ultrasonic sensor. By default, the code assumes that the trigger pin is connected to pin 9 and the echo pin is connected to pin 10.
When connecting the ultrasonic sensor to the Arduino board, ensure that the trigger pin of the sensor is connected to the trigger pin specified in the code (TRIGGER_PIN) and the echo pin of the sensor is connected to the echo pin specified in the code (ECHO_PIN). This is important for the proper functioning of the distance measurement.
If you have connected the ultrasonic sensor to different pins on the Arduino board, you need to modify the TRIGGER_PIN and ECHO_PIN constants in the code accordingly. Update these constants to match the pins you have used for connecting the sensor.
For example, if you have connected the trigger pin of the sensor to pin 7 and the echo pin to pin 8, you would modify the code as follows:
#define TRIGGER_PIN 7
#define ECHO_PIN 8
After making the necessary changes, upload the code to your Arduino board and ensure that it is properly connected to the ultrasonic sensor. Open the serial monitor in the Arduino IDE at a baud rate of 9600 to view the distance readings. You should see the distance measurements displayed, which have been smoothened using the moving average filter.
ABOUT THIS PROJECT
Distance Measurement using Arduino Ultrasonic Sensor is a very easy project to measure shorter distance precisely. Before getting started you must know about Ultrasonic Sensor HC SR-04, which is a low-cost sensor. The ultrasonic sensor is consists of Transmitter and Receiver modules. Transmitter part ejects the pulse out and the receiver part receives the pulse. If an obstacle is placed before the sensor, the transmitted pulse ejected strike the obstacle and reflected back. The reflected pulse is received by the receiver part. The time between transmission and reception is calculated. This data is processed to calculate distance.
In this project, we are going to interface Ultrasonic sensor HC-SR04 with Arduino and LCD Display. The ultrasonic sensor is used to measure the distance. It acts as a Sonar. It sends an ultrasonic wave of a certain frequency that comes back after hitting the object and calculates the time traveled by it. So let’s learn about Distance Measurement Using Arduino & HC-SR04 Ultrasonic Sensor.
components Used
Arduino Uno or Pro Mini
Ultrasonic sensor Module
16x2 LCD
Scale
Bread board
9 volt battery
Connecting wires
Ultrasonic Sensor Module
There are many types of Arduino distance sensors, but in this project we have used the HC-SR04 to measure distance in range of 2cm-400cm with an accuracy of 3mm. The sensor module consists of an ultrasonic transmitter, receiver and control circuit. The working principle of ultrasonic sensor is as follows:
High level signal is sent for 10us using Trigger.
The module sends eight 40 KHz signals automatically, and then detects whether pulse is received or not.
If the signal is received, then it is through high level. The time of high duration is the time gap between sending and receiving the signal.
Distance= (Time x Speed of Sound in Air (340 m/s))/2

Timing Diagram
The module works on the natural phenomenon of ECHO of sound. A pulse is sent for about 10us to trigger the module. After which the module automatically sends 8 cycles of 40 KHz ultrasound signal and checks its echo. The signal after striking with an obstacle returns back and is captured by the receiver. Thus the distance of the obstacle from the sensor is simply calculated by the formula given as
Distance= (time x speed)/2.
Here we have divided the product of speed and time by 2 because the time is the total time it took to reach the obstacle and return back. Thus the time to reach obstacle is just half the total time taken


The circuit diagram for arduino and ultrasonic sensor is shown above to measure the distance. In circuit connections Ultrasonic sensor module’s “trigger” and “echo” pins are directly connected to pin 18(A4) and 19(A5) of arduino. A 16x2 LCD is connected with arduino in 4-bit mode. Control pin RS, RW and En are directly connected to arduino pin 2, GND and 3. And data pin D4-D7 is connected to 4, 5, 6 and 7 of arduino.
First of all we need to trigger the ultrasonic sensor module to transmit signal by using arduino and then wait for receive ECHO. Arduino reads the time between triggering and Received ECHO. We know that speed of sound is around 340m/s. so we can calculate distance by using given formula:
Distance= (travel time/2) * speed of sound
Where speed of sound around 340m per second.
A 16x2 LCD is used for displaying distance.
Find more about the working of distance measurement project in this tutorial: Distance measurement using ultrasonic sensor and AVR Microcontroller.
Arduino Ultrasonic Sensor Code for Distance Measurement
The complete code for this ultrasonic distance measurement project is given at the bottom of this page. In the code we read time by using pulseIn(pin). And then perform calculations and displayed result on 16x2 LCD by using appropriate functions.
Distance measurement program
Code
#include
#define trigger 18
#define echo 19
LiquidCrystal lcd(2,3,4,5,6,7);
float time=0,distance=0;
void setup()
{
lcd.begin(16,2);
pinMode(trigger,OUTPUT);
pinMode(echo,INPUT);
lcd.print(" Ultra sonic");
lcd.setCursor(0,1);
lcd.print("Distance Meter");
delay(2000);
lcd.clear();
lcd.print(" Circuit Digest");
delay(2000);
}
void loop()
{
lcd.clear();
RESULT;
int trigPin = 11; // Trigger
int echoPin = 12; // Echo
long duration, cm, inches;
long sum=0;
long avg;
int i;
void setup()
{
//Serial Port begin
Serial.begin (9600);
//Define inputs and outputs
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop()
{
// The sensor is triggered by a HIGH pulse of 10 or more microseconds.
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
digitalWrite(trigPin, LOW);
delayMicroseconds(5);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the signal from the sensor: a HIGH pulse whose
// duration is the time (in microseconds) from the sending
// of the ping to the reception of its echo off of an object.
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);
// Convert the time into a distance
cm = (duration/2) / 29.1; // Divide by 29.1 or multiply by 0.0343
inches = (duration/2) / 74; // Divide by 74 or multiply by 0.0135
for (i=0; i<5; i++)
{
sum=sum+inches;
avg = sum/5;
}
Serial.print(avg);
Serial.print("Avg, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
Serial.print(inches);
Serial.print("in");
Serial.println();
delay(250);
}
Circuit Diagram: