I am working on a project that uses ultrasonic HC-SR04 sensor to measure distance. I've connected the sensor to the Arduino Uno board, I am also using Arduino IDE to program the Arduino. The problem is that I am not getting stable readings, there is the presence of some noise in the readings. How should I filter out this noise.

Circuit connections are as follows:

Ultrasonic sensor | Arduino
VCC                 5V
GND                 GND
Trigger             12 (digital)
Echo                11 (digital)

I am using new ping to measure distance.

2 Answers 2


Having noise in the sensor data is common and normal, especially on low end sensor.

As you can imagine there is a "data science" to clean up the values, mostly based on statistic.

One of the easiest trick is to remove all values that have a difference > Xt from previous value; as you can imagine the tolerance Xt is calculated by a factor X, let's say a bit more the maximum speed you think the system will operate in time multiplies by the time since the last valid measure.

For example you expect a max distance chance of 10m in one second, so we use as tolerance 15m/s. If we don't read valid value, after 6 seconds our tolerance is 15m/s * 6s = 90m

Of course after much time maybe you just want to accept the first reading that seems valid, so you analyze 10, 100, 1000 value and see if they seems correct.

Then for a quick and dirty smoothing and cleaning if the remaining data, you can run a average on the value, there are different forms, and more value you use more stable are your output, but also less fast to follow changes.

A kallmann filter is the most common but also complex way to clean the data, but I guess in most hobbyist application is just overkill.


First off, Start a time counter. You can get the current time instant by using:

unsigned long StartTime = millis();

After that, keep counting time by using the following block:

 unsigned long elapsedTime = currentTime - StartTime;

With this you can know how much time (in ms) has passed since StartTime. In this time loop, keep reading data from the Ultrasonic sensor. As the sensor may need some time to get each reading, take a conservative delay (e.g. 100 ms). You can again increment the timer by using a goto statement. Note that you must also maintain a counter for later. In this time loop, keep adding the readings from the sensor to itself. Finally when the stipulated time is over, you can take the average by dividing the final sum of the sensor values with the counter maintained earlier.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.