Jump to content






Averaging HC-SR04 ultrasonic distance sensor readings in a non-blocking manner

Posted by Nathan House, in Programming 08 July 2013 · 2,255 views

This is a reply to a facebook post. It would have been difficult to read in facebook's narrow layout, so I'm posting it here.

In order to average three readings from a sensor in a non-blocking manner, you could either have three variables like this:
int ultrasonicReading0 = 0;
int ultrasonicReading1 = 0;
int ultrasonicReading2 = 0;
A variable to store the average distance in:
int averageDistance = 0;
And then another variable to keep track of which value you are currently storing:
int currentUltrasonicReading = 0;
Or you could have an array of integers instead of three separate integers. Then, when you read from the sensor you would have something like this:
if(currentUltrasonicReading == 0)
{
    ultrasonicReading0 = (pulseIn(utlrasonic2EchoPin, HIGH)/2)/29;
    currentUltrasonicReading++;
}
else if(currentUltrasonicReading == 1)
{
    ultrasonicReading1 = (pulseIn(utlrasonic2EchoPin, HIGH)/2)/29;
    currentUltrasonicReading++;
}
else if(currentUltrasonicReading == 2)
{
    ultrasonicReading2 = (pulseIn(utlrasonic2EchoPin, HIGH)/2)/29;
    currentUltrasonicReading++;
}
else
{
    averageDistance = (ultrasonicReading0 + ultrasonicReading1 + ultrasonicReading2)/3;
    currentUltrasonicReading = 0;
}
This may seem like an overly complicated way of doing things, but non-blocking code is always better even if it adds complexity to your program. Also, I'm sure the above code could be optimized, I just came up with this quickly as an example.

  • 0