Inaccurate readings of Distances (HC-SRO4)

Hi guys! This is my first time in this website. Just newly found out this community of robot enthusiasts, so I guess, and I hope you can help me with this problem, and by the way, I'm also a beginner of this one..

 

I just brought an ultrasonic sensor. Well it's working well after testing it with a code. But once I put some "if, else" statements, it's giving me inaccurate distances...

for instance... if I give the loop as ReadDist(); (// It is assumed that I've already put the right code for the Ultrasonic Sensor).

void loop()

{

   ReadDist();

}

... then its giving me accurate distances in inches in the serial monitor...

(5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5) // so with that, we can conclude that it's working well with readings saying that the object is still in front without any movements...

but with this...

void loop()

{

  ReadDist();

  if (inches > 3)

  {

     forward();

     delay(100);

}

else

{

   halt();

   delay(100);

}  

the readings are very inaccurate... (5,5,0,5,5,5,0,5,0,5,0,5,0,5,0,0,5,5 and so on...) it's causing the wheels to stop for 0.1 sec. every time it drops to 0 , a thing that I dont want to happen for the distance that I gave from the sensor is still greater than 3 inches...

 

What could be the possible reasons why it's happening? any advices/suggestions guys?

 

- Ellimenopy

HC-SR04

I have observed the same behavior with the $2.00US modules. There are some Google references to changing a cap on the module to get better results. You might also just discard the obviously bad results and retry. My solution was to trash the modules and get better quality units. You could change the delay(100) to delay(50) and do twice as many sonar cycles. 

My first guess is that you

My first guess is that you are getting a voltage drop when the robot moves forward and the sensor is going below its threshold to work accurately, hence the unusual errors.  To solve, put some capacitors on the line to your ultrasonic sensor and that will help with the voltage dipping below its threshold as the robot 

My next guess and probably the more likely is that because the bot is moving, and/ or you are so close to the target, you are getting odd bounce backs which the sensor doesn’t know what to do with.  These sensors have a range that they are supposedly accurate in which you can’t really trust.  Closer in is a lot more inaccurate than farther away.  What do you expect for a few bucks?!  What I have done in the past is I will save the last 5 or 10 numbers, remove the highest and the lowest, then average the rest to get a fairly accurate number.  I have noted a wide variety of quality when it comes to these sensors.  Some work really well and you don’t have to do any of the sampling while others…  

I hope this helps.  Let us know how you make out.

Regards,

Bill