Improving readings from the HC-SR04

In my previous post on the accuracy of the HC-SR04 ultra-sonic range finder I found that there were issues that needed to be compensated for. However, using it in practice revealed further difficulties…

The HC-SR04 had a habit of returning a value of 0.0 or distances ridiculously outside of its possible range. Therefore the rangeFinder() function need to correct for this.

float rangeFinder()
{ 
  unsigned int uS = sonar.ping_median(30);
  float x = (uS/2.0)/29.0;
  while(x < 3 || x > 35)
  {
    Serial.println("rangeFinder out of range!");
    uS = sonar.ping_median(30);
    x = (uS/2.0)/29.0;
  }
  return x;
}

The rest of the sketch set up is the same as my previous post. I’ve added a while loop to keep gathering new values until the HC-SR04 delivers something within the desired range (and then it’s safer to assume it’s not some strange outlier). I’ve set the lower limit at 3cm because while the data sheet states it can go as low as 2cm my tests show that they get very unreliable after 3cm. I factored this difficulty with distances below 3cm by moving the sensor further back in my design, giving a -1cm offset.

The upper limit is set at 35cm because in my project it’s impossible to measure a range above that. You could set the upper limit at the maximum range (400cm according to the data sheet), but be mindful that you could get stuck in the while loop if there’s nothing to return. Therefore, if you do not know the upper limit you could remove it from the while test:

float rangeFinder()
{ 
  unsigned int uS = sonar.ping_median(30);
  float x = (uS/2.0)/29.0;
  while(x < 3)
  {
    Serial.println("rangeFinder out of range!");
    uS = sonar.ping_median(30);
    x = (uS/2.0)/29.0;
  }
  return x;
}

Overall, the HC-SR04 is best described as inaccurate and unreliable, but factoring this into your design can give you something that’s cheap and usable. Interestingly, the data sheet suggest that the surface to be detected needs to be around 0.5m². Yet, the objects I’m using it to detect (filling cups) are much smaller. This could account for some of the difficulties I encountered in it’s usage. However, with a measurement angle of 15 degrees, at short the short ranges I’m using it (3-35cm), the objects I’m detecting should fill its sensory field.

And that’s it from me on using this belligerent sensor. Feel free to leave your thoughts, suggestions and improvements in the comments below.

Advertisements

~ by Jay on December 29, 2014.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: