I feel dumb
June 5, 2014
It all started when I was programming PopPet. I was using the simple way of using the HC-SR04:
long duration, distance;
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
This was all well and good except for one thing. If there is no echo from the ping, the pulseIn hangs and freezes the code for a whole second.
This wreaked havoc on the simplest obstacle avoidance routine as the bot would just spin in a circle. I wanted to conquer this delay, so I went to google and started looking for ways to be rid of the pulseIn.
My first thought was to run some sort of micro timer and manually calculate the distance by calculating the time it took to go high to low with a micros subtraction.
This didn't work for me. I figure I was too simplistic in my code or was barking up the wrong tree. So I decided to see if I could use a for loop. Using a for loop I could attempt to trigger the trig pin and set a timer, if no echo is heard in that time frame it exits and returns a 0. This also didn't work.
I came to the SB to see if someone could spark my next idea, Basile did not disappoint. He mentioned the NewPing library.
Many of you know that the NewPing library makes the use of such ultrasonic sensors much easier, no tricky timings are needed, you just need to tell it to trigger and it triggers.
One of the big benefits of this library though is the fact that is does not have this one second delay. I did no however want to import the whole library into the sketch as I am using the DAGU Mini Driver, a great board, but small on space.
Basile mentioned looking in the actual library files and seeing how they did it. Let's just say I spent way to long trying to figure it out. Being the first time looking at a library I was confused how it all linked and in the end I resorted to a bag of chips and Dr.Phil.
After my brief session watching stupid people, and making myself feel better, I returned to the conundrum at hand. I thought, hey, why not look up what the Arduino site has to say about pulseIn. This is when I realized I was dumb.
Little did I know that the pulseIn function actually has a timeout feature, and by default, this value is one second. All I had to do was set the timeout value much lower and guess what, the bastard of a thing worked perfectly. Absolutely no lag at all and incredibly quick sensor readings, faster than I can actually physically test.
Moral of the story? RTFM and don't be an dumb dumb head.
duration = pulseIn(echoPin, HIGH, 2000);