Arduino Forum

Using Arduino => Sensors => Topic started by: mjbmikeb on Mar 12, 2011, 03:04 pm

Title: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: mjbmikeb on Mar 12, 2011, 03:04 pm
I'm trying to use a HC-SR04 ultasonic distance sensor from Ebay (http://cgi.ebay.com.au/ws/eBayISAPI.dll?ViewItem&item=280640838032),
but it doesn't appear to have an internal timeout for when it fails to detect an echo.
This sometimes results in the echo line staying high forever, even if you re-trigger a measurement.
The only way to get it to reset is by cycling the power.

The spec for the HC-SR04 is somewhat incomplete, however research indicates that this is a copy of the (Devantech) SRF04 sensor from the following site, http://www.robot-electronics.co.uk/htm/srf04tech.htm.
The spec for this says that "If nothing is detected then the SRF04 will lower its echo line anyway after about 36mS.".

My HC-SR04 sensor doesn't do this. Does anyone else have the same sensor with a working timeout?

The vendor has scrubbed the IDs off the chips so I don't hold much hope for doing a retro-fix.
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: AWOL on Mar 12, 2011, 03:11 pm
Quote
however research indicates that this is a copy of the (Devantech) SRF04

I've been using the Devantech devices for over ten years without any problems like you describe.
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: mare19 on Mar 21, 2011, 07:54 pm
i think i have the same problem... my hc-sr04 is measuring the distance with no problems. but if there is no object in range, i become a 0 value and the sensor hangs and any next value ist 0 even when there are objects....
i should get 3 other sensors this week, so i'll tel you..
sry for my eng.. :smiley-roll:
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: mjbmikeb on Apr 10, 2011, 08:18 am
Did you have the same problem with the other sensors?
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: mjbmikeb on Apr 23, 2011, 05:11 pm

Following up to myself....

I'm driving the sensor power rail from an Arduino pin and if the echo PWM signal gets stuck because of no echo I cycle the power off for 100ms, then wait for 100ms before taking a reading.
So far it's been working very well.
With this sensor I get distance resolution of about 1mm  which is better than the spec of 3mm and much better than a DF Robotics sensor which only seems to measure in 10mm increments even when using the PWM output.
Jitter is only about 2us in a 1448us round trip at a distance of 25cm, which equates to 0.14%.
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: SubMicro on Aug 18, 2011, 02:27 am
Sorry to hijack your post, but I have a question for you. What kind of range do you get with yours? Mine seems to have a very limited range of about 5cm. Perhaps i'm coding incorrectly. What formula do you use to convert output to in/cm?

I've tried several examples always the same result.....
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: mjbmikeb on Aug 18, 2011, 05:20 am
Max range to a flat hard perpendicular surface is about 1.5 meters.

The distance formula is given here.
http://arduino.cc/en/Tutorial/Ping?from=Tutorial.UltrasoundSensor

5cm does not sound right at all.

Do you have access to an oscilloscope?

Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: SubMicro on Aug 26, 2011, 02:56 am
Sorry it's on the "I really need one but can't afford it list!" Any way it's just an ID10T prob or are my sensors bad? I know you can't tell with out testing, but what tests can I do lacking an Oscilloscope?
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: AWOL on Aug 26, 2011, 09:59 am
Quote
but what tests can I do lacking an Oscilloscope

Train your pet bat to flap its wings when it hears a 40kHz pulse?
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: SubMicro on Aug 27, 2011, 08:03 pm
Well funny as that may be, XD I'm still in need of guidance here. I'm gonna start a new post. I feel bad hijacking this one. sorry
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: jameshappy on Sep 27, 2011, 09:26 am
This timout thing bugged me too. I applied a bit of RTFM strategy and found a solution. Good luck, and please let me know if this helps you.
Code: [Select]




// JamesHappy
// Arduino UNO 0022
// Demonstration sketch of HC-SR04 Ultrasonic Range Finder with echo timeout

// Onboard LED should blink while searching for surface
// Onboard LED should be solid when surface is within a specified distance
// Rangefinder should only wait for echos under a calculated timeout

// Reference: http://www.elecfreaks.com/244.html
// Reference: http://www.arduino.cc/en/Reference/PulseIn
// Note: HC-SR04 tested successful in both 5v and 3.5v

int iTrigger     = 2;  // Digital Pin 2
int iEcho        = 3;  // Digital Pin 3
int iAlertLED    = 13; // Digital Pin 13
int iEchoTimeout = 0;  // In Microseconds
int iMaxDistance = 20; // In Centimeters

int iTriggerPullDown = 2;  // In Microseconds
int iPingWidth       = 10; // In Microseconds

void setup() {
  pinMode(iTrigger,OUTPUT);
  pinMode(iEcho,INPUT);
  pinMode(iAlertLED, OUTPUT);
  iEchoTimeout = iMaxDistance*2*29;
}

void loop() {
  digitalWrite(iTrigger, LOW);
  delayMicroseconds(iTriggerPullDown);
  digitalWrite(iTrigger, HIGH);
  delayMicroseconds(iPingWidth);
  digitalWrite(iTrigger, LOW);
  unsigned long ulPing = pulseIn(iEcho,HIGH,iEchoTimeout);
  if(ulPing) {
    digitalWrite(iAlertLED, HIGH);
    SimulateLoad(250);
  }
  else {
    digitalWrite(iAlertLED, HIGH);
    delay(25);
    digitalWrite(iAlertLED, LOW);
    SimulateLoad(225);
  }
}

void SimulateLoad(int iDutyCycle) {
  delay(iDutyCycle);
}

Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: vasimv on Mar 18, 2015, 05:50 pm
Just ran into same problem too with HC-SR04. Tried to reset sonar's CPU by sending pulse to pin 7, but didn't help. For me it looks like analog part of the module works like some sort of trigger if there no enough external noise in background (yes, it did help when i just clap near module - starts working again).

So, i've doing pulse to discharge C9 capacitor ( http://kazus.ru/forums/attachment.php?attachmentid=75731&d=1423821255 ) by connecting it to one of digital pins of arduino through 500 ohm resistor (setting in INPUT mode, without pull-up most of time, OUTPUT mode + LOW for pulse). Needs a small delay to recharge the capacitor to right level after the pulse.
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: toedip on Apr 10, 2015, 08:43 pm
Hey,

I've been looking around for solutions for my sensors I just purchased. It will work fine, then all of a sudden it will keep returning 0. I have 4 from Sainsmart and they all seem to operate the same.

Vasimv has the only post so far that gave me some light in that, if I snap my fingers beside the sensor, 100% of the time it will start reporting distance again. At least for some random amount of time, till it starts to 0 out again. (usually a few seconds, some times even a few minutes)

Vasimv, would you be able to elaborate on your solution. I do not quite understand how you are discharging C9.

Are you sending it to a digital input and giving it an INPUT mode? or an OUTPUT mode? I'm a little confused you mentioned both.
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: vasimv on Apr 26, 2015, 05:32 pm
Are you sending it to a digital input and giving it an INPUT mode? or an OUTPUT mode? I'm a little confused you mentioned both.
The pin should be in INPUT without pull-up all time (otherwise it'll mess divider's voltage on C9). When you need to reset the sensor - make it OUTPUT mode, LOW set, then some delay and switch to INPUT/no-pullup again.

#define resetPin 3 /* D3 to C9 */

void reset_hcsr04 () {
pinMode(resetPin, OUTPUT);
digitalWrite(resetPin, LOW);
delay(1);
pinMode(resetPin, INPUT);
digitalWrite(resetPin, LOW);
}


Btw, i have idea that positive pulse on C9 could reset the sensor too (you have just put diode between C9 and trigger PIN, so positive pulse that starts the sensor - will "shock" the analog part and it'll start working if got locked up). But didn't test yet.
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: SaintGimp on May 12, 2015, 11:23 am
Some knock-off models of the HC-SR04 do not implement a timeout if no echo is detected at all.  In that case, the echo pin will simply remain high forever and will not generate any new pings, regardless of what you do with the trigger pin.  The original model from Robot Electronics (http://www.robot-electronics.co.uk/htm/srf04tech.htm) times out after 36 ms and does not have this problem, but many (all?) cheap knock-off models do.

You can reproduce the problem easily by covering the receiver transducer with your thumb, then removing your thumb.  If your sensor doesn't have a timeout, it will stop generating pings and the only way to recover is to power cycle the sensor.

A workaround that works for me so far is to test the state of the echo pin 100 ms after triggering a ping.  If it's still high, you're in a stuck state.  If you wire power to the sensor through a transistor and control that transistor via another pin, then you can power cycle the sensor via software and get back to a working state.
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: letch on May 13, 2015, 02:03 pm
put a 3MOhm restist between the pin 4 and 9 from the U1 EM78P153S Controller, now it works!

best regards
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: docdoc on May 20, 2015, 03:06 am
I worked hard on this issue (I bought that f***ing SRF04, next time I'll get SRF05!) and I think I SOLVED it, and WITHOUT ANY ADDITIONAL HARDWARE!
When I detect the sensor is stuck, I simply switch echo pin to OUTPUT, put it into LOW state, and after a while re-set it to INPUT, then cycle again.
This is a code example to explain my solution:
Code: [Select]

// ... this is the reading loop
    long pulseDuration;
    long distance;
    int tries = 0;
    do
    {
        pulseDuration = pulseIn( echoPort, HIGH, 50000);
        distance = 0.034 * pulseDuration / 2;
        if ( pulseDuration == 0 ) {
            delay(100);
            pinMode(echoPort, OUTPUT);
            digitalWrite(echoPort, LOW);
            delay(100);
            pinMode(echoPort, INPUT);
        }
    } while (pulseDuration == 0 && ++tries < 3);
    if (pulseDuration == 0)
      // Out of range
    else
      // Read ok!

Hope it helps!
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: toedip on May 28, 2015, 07:25 pm
Hi.

I tried the 3Mohm resistor from pin 4-9. It never seems to time out, (which is good), however it seems to only read up to 60cm.

I may try the approach that SaintGimp mentioned. I thought of doing something like this before, just never got around to implementing it.

Cheers,
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: kiwilee on May 29, 2015, 11:34 am
Hey, thanks docdoc this really works! Would be good to get this in as an option in NewPing for dodgy hardware. Thanks so much, have been tearing my hair out. Sensor works OK now, making a big three way sensor around tree for kids at school, this was very helpful, thanks.

I worked hard on this issue (I bought that f***ing SRF04, next time I'll get SRF05!) and I think I SOLVED it, and WITHOUT ANY ADDITIONAL HARDWARE!
When I detect the sensor is stuck, I simply switch echo pin to OUTPUT, put it into LOW state, and after a while re-set it to INPUT, then cycle again.
This is a code example to explain my solution:
Code: [Select]

// ... this is the reading loop
    long pulseDuration;
    long distance;
    int tries = 0;
    do
    {
        pulseDuration = pulseIn( echoPort, HIGH, 50000);
        distance = 0.034 * pulseDuration / 2;
        if ( pulseDuration == 0 ) {
            delay(100);
            pinMode(echoPort, OUTPUT);
            digitalWrite(echoPort, LOW);
            delay(100);
            pinMode(echoPort, INPUT);
        }
    } while (pulseDuration == 0 && ++tries < 3);
    if (pulseDuration == 0)
      // Out of range
    else
      // Read ok!

Hope it helps!

Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: Slimicus on Jun 10, 2015, 07:16 pm
I'm using the HY-SRF05 (the one from Upgrade Industries sold by robot-electronics,) which I bought because they stated it is supposed to time out and it doesn't time out. I contacted their (the manufacturer, Upgrade Industries) support to find out what's happening and here's what i sent them:



Quote
I've been having a problems with a lot of the common SRF04 and SRF05 Ultrasonic rangers, and in this case I'm using the HY-SRF05. I thought this one might operate better than the others because the datasheet indicates that if nothing is detected, the sensor will time out after 30 ms

(This is the one I'm referring too, but there are many other similar ones out there)
http://www.robotstorehk.com/sensors/doc/srf05tech.pdf

Specifically:
"If nothing is detected then the SRF05 will lower its echo line anyway after about 30mS."

So that means this sensor could range about 20 times in a second. The problem I'm seeing is that it's take over 200ms for the sensor to time out when no object is detected. It's a very easy to reproduce problem, just point the sensor at nothing, and attach a scope to the echo pin and the trigger pin, then trigger on the scope on the trigger pin and watch as the echo pin goes high and doesn't come back down for 200ms.

Do you know if there could be any odd error in the code below? I've tried many of these sensors, they all behave the same way but the data sheet for this and even other brands indicates they should be able to return low around 30-40ms after no object is detected.

I've attached copies of the scope output, the echo pin is on Channel 4, and the measurements at the bottom show the "Width" of the pulse in the dark blue color.

The easy way around this problem is to read the echo pin after the pulse times out and make sure you don't try to trigger if it's still high, if you don't set a timeout, I've found so far that all of them eventually do come back, but the amount of time it takes to return is variable within a range depending on the particular device.

For example, this Hy-SRF05 is around 220ms (it varies about 20ms either way) and other brands I've tested come in at 180ms and 200ms. I've tried dozens of these from many vendors, and I have yet to find one that properly times out. Hy-SRF05 was my biggest hope too, but even their sensor behaves the same way.

Of course I don't want to only be able to Scan 4 times a second, and it seems when the sensor is past the 50ms mark, it won't retrigger for any reason unless it receives a pulse from another sensor or it reaches the 200ms (or whatever the range for that model is) mark.
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: docdoc on Jun 23, 2015, 11:26 pm
I'm using the HY-SRF05 (the one from Upgrade Industries sold by robot-electronics,) which I bought because they stated it is supposed to time out and it doesn't time out.
After my last post here I bought an HY-SRF05 also, and it seems to work fine... I mean, if it timeouts I get a 0 cm distance most of the times, but without the long delays you're complaining about. Don't know if yours is an issue of a somehow "buggy" series...

Please note I said "most of the times" returns zero, because mine has a small quirk: it seems to return an anomalous 3 cm distance alternated to (correct) zero, so I return "0" if current measure is 3 cm and the previous one was 0. And it worked fine this way.

So, the reason why I delayed this reply to original post is I made a library to help me (and anyone with the same problem too) manage either SR-04 or SRF-05 idiosyncrasies..:-) I hope you enjoy it, but I'll appreciate any feedback as I'm open to any suggestions and critics... ;)

Please note the class is called SRF05, but it works with both SRF05 and SR04.

After installing the library, open the example:
Code: [Select]
// SENSOR DEMO
#include "SRF05.h"

// trigPin, echoPin, MaxDist, readInterval
SRF05 Sensor(6, 7, 200, 500);

void setup() {
    Serial.begin(9600);
// If using SR04 enable the following line:
//Sensor.Unlock = true;
}

void loop() {
    // Distance read
    if ( Sensor.Read() > -1 ) {
        // New distance reading!
        if ( Sensor.Distance == 0 ) {
            Serial.println("Out of range");
        } else {
            // -------------
            Serial.print("Dist: ");
            Serial.print(Sensor.Distance);
            Serial.println(" cm");
        }
    }
}
As you can see, we simply create an SRF05 object with needed configuration parameters:

The first two don't need particular explanations I hope, while the third simply specifies the maximum distance we want to measure, usually not higher than sensor range.
ReadInterval makes it easy to manage reading intervals without a specific timer: usually we don't check the distance on every loop() call, so set ReadInterval to the desired milliseconds and the library will do the job for you.

This way, the loop() calls only the "Read()" method: it returns measured distance in centimeters but if called before "ReadInterval" milliseconds after the last read, it returns "-1" meaning "it's not the time!". 8)
If called after ReadInterval milliseconds or more, performs a new ping and returns the updated distance. If the sensor doesn't read obstacles within the range (no echo or echo after "MadDist" cm), the Read() method returns zero.

If for any reason you need to continuously read the distance, simpy set ReadInterval=0 and each Read() call will ping the sensor.

Apart from Read(), some public properties are available anyway, including constructor parameters and latest measured distance:

Library version 1.1 (attached one) includes a workaround for "locking" SR04 sensors when no echo is received. To enable this feature simply set "Unlock=true;" inside "setup()", as shown in the example.
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: orje on Jul 23, 2015, 08:25 pm
I also had the problem that the sensor stayed HIGH when it couldn't reflect anything.
I tried to solve the problem through switching the Arduino ECHO input into output mode and setting it LOW, like docdoc it adviced. But this didn't help.
The direct power connect of the sensor to a Arduino output like mjbmikeb wrote worked either. It didn't hung but didn't also measure at all.
The only thing that helped was what SaintGimp wrote, to power the sensor over a transistor and switch that shortly off if the sensor hangs.
Nevertheless thanks to all for your effort.
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: docdoc on Jul 24, 2015, 12:10 am
Yep, that's why I bought an SRF-05 and I'll never buy SR-04 anymore...
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: Vinterwoo on Sep 15, 2015, 02:13 am
I had the same problem, but docdoc's solution worked for me.

Thanks docdoc!

Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: docdoc on Sep 15, 2015, 04:15 pm
You're welcome, I'm happy to see someone else solved this problem with this "too chinese" SR04! ;D

Btw, just to know, did you included my SRF05 library (and used Unlock=true) or changed your code?

Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: teckel on Sep 16, 2015, 08:03 pm
Or, you could use the NewPing  (https://forum.arduino.cc/index.php?topic=106043.0) library which has this and many other advantages (smaller code size, one pin mode, timer interrupt method, etc.).

Tim
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: docdoc on Sep 16, 2015, 08:53 pm
Are you sure NewPing fixes SR04 "lockout" on echo timeout?
I have seen nothing about this in its docs...

Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: teckel on Sep 16, 2015, 11:03 pm
Are you sure NewPing fixes SR04 "lockout" on echo timeout?
I have seen nothing about this in its docs...


That was the primary reason NewPing was written 3 years ago.  It's evolved from there.  This feature is listed as bullet item #3 in the introduction:

Doesn't lag for a full second if no ping echo is received like all other ultrasonic libraries.

NewPing (https://bitbucket.org/teckel12/arduino-new-ping/wiki/Home)


Tim
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: docdoc on Sep 19, 2015, 05:05 pm
That was the primary reason NewPing was written 3 years ago.  It's evolved from there.  This feature is listed as bullet item #3 in the introduction:
Doesn't lag for a full second if no ping echo is received like all other ultrasonic libraries.
Yeah, but i think you haven't got the point, that's not the problem I'm talking about (and solved with my lib)...

My SR04 sensor(s) doesn't simply "lag for a second" if no echo is received, it completeliy LOCKS UP, returning 0ms for all and every subsequent reads, until turned off and on, as suggested in other topics (using a pin to control a transistor to simulate physical disconnection of SR04 power cable). I still don't know if my SR04 (and the one used by many other users here) is a faulty series, or made by a "too-much-chinese" factory, by the way the problem was real and NewPing didn't solve it. After trying with 3 different SR04, I decided to buy SRF05 from now on, btw SF04 is a bit cheaper and I wanted to use them for low-purpose projects, and with my SRF05 library I have full control over it, without any hardware change!



Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: teckel on Sep 21, 2015, 03:05 pm
Yeah, but i think you haven't got the point, that's not the problem I'm talking about (and solved with my lib)...

My SR04 sensor(s) doesn't simply "lag for a second" if no echo is received, it completeliy LOCKS UP, returning 0ms for all and every subsequent reads, until turned off and on, as suggested in other topics (using a pin to control a transistor to simulate physical disconnection of SR04 power cable). I still don't know if my SR04 (and the one used by many other users here) is a faulty series, or made by a "too-much-chinese" factory, by the way the problem was real and NewPing didn't solve it. After trying with 3 different SR04, I decided to buy SRF05 from now on, btw SF04 is a bit cheaper and I wanted to use them for low-purpose projects, and with my SRF05 library I have full control over it, without any hardware change!
Sounds like you have a faulty sensor.  Obviously, it shouldn't stop working if it doesn't get a ping echo.  I have dozens of sensors, and none do that.  But, sounds like testing the state of the echo pin when a 0ms ping is received and if it's locked up cycling power to the sensor seems like the simple thing to do.

There's no need for a transistor to power the sensor to do this, the sensor doesn't draw much power so you can supply power directly from an Arduino pin.  Using my NewPing library and the one pin method, you could probably still control the sensor with just two pins (one for power and one for trigger/echo).  I do this with a ultra low power sensor that combines a PIR sensor and an ultrasonic sensor.  The PIR sensor detects motion, and if detected it activates a pin which turns on the ultrasonic sensor to get a distance measurement.  Not only does this reduce the power used to a trickle (using a pin interrupt), it also allows for a mostly passive sensor (except for the distance measurement).

Anyway, if this is just a defective sensor, I would think getting a working sensor would be the correct solution (as they cost about $1).  If there's a model of sensor that does this by design (not sure why), I would like to have one so my library could be modified to accommodate it.  It seems testing pin state when getting a 0cm result and cycling power would the easy thing to do.  Or something simple like this which is done after a ping:

Code: [Select]
  if (cm == 0 && digitalRead(ECHO_PIN) == LOW) {
    pinMode(ECHO_PIN, OUTPUT);
    digitalWrite(ECHO_PIN, LOW);
    delay(100);
    pinMode(ECHO_PIN, INPUT);   
  }


But, there's really no way for NewPing to be modified if no one can source a sensor that has this problem.  Also, there's a question of if anything should be done if it's just a defective sensor.  Heck, I'm not even sure the sensors are defective, maybe some people are just doing something else incorrectly.  In any case, can't know and can't really attempt to fix a problem that doesn't exist (at least for me).

Tim
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: docdoc on Sep 21, 2015, 06:03 pm
Yep, Tim, I agree it'd be a faulty sensor series (I already said I suspect the sensor is "too-much-chinese", no? :-) ), even if I have 3 of them, bought from two different ebay stores (none of them chinese), but other users also reported the same issue I experienced, so it's not so rare. So I solved definitely the problem buying some SRF05 instead of the cheaper SR04, but I wanted to make my library still compatible.

If you agree, I'd like to contribute to NewPing by suggesting you to add a workaround for those "faulty" sensors, to let it cover even such "chinenest" :-) ones: if SR04 is in this "locked" state it always returns zero "pulse duration" immediately, so this is what you could track down. This is the code portion of my workaround (looks similar to yours, I use "pulseDuration" variable you use "cm"), where the feature si activated if "Unlock" public variabile is set to true:

Code: [Select]

if ( Unlock && pulseDuration == 0 ) {
  // SR04 unlock
  pinMode(EchoPin, OUTPUT);
  digitalWrite(EchoPin, LOW);
  delay(100);
  pinMode(EchoPin, INPUT);
}


As I see no similar solution inside NewPing, I think you could include it in next NewPing release, if you want to. And adding an explicit reference to this issue, and how to fix it by setting "Unlock=true".
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: teckel on Sep 21, 2015, 09:06 pm
Yep, Tim, I agree it'd be a faulty sensor series (I already said I suspect the sensor is "too-much-chinese", no? :-) ), even if I have 3 of them, bought from two different ebay stores (none of them chinese), but other users also reported the same issue I experienced, so it's not so rare. So I solved definitely the problem buying some SRF05 instead of the cheaper SR04, but I wanted to make my library still compatible.

If you agree, I'd like to contribute to NewPing by suggesting you to add a workaround for those "faulty" sensors, to let it cover even such "chinenest" :-) ones: if SR04 is in this "locked" state it always returns zero "pulse duration" immediately, so this is what you could track down. This is the code portion of my workaround (looks similar to yours, I use "pulseDuration" variable you use "cm"), where the feature si activated if "Unlock" public variabile is set to true:

Code: [Select]

if ( Unlock && pulseDuration == 0 ) {
  // SR04 unlock
  pinMode(EchoPin, OUTPUT);
  digitalWrite(EchoPin, LOW);
  delay(100);
  pinMode(EchoPin, INPUT);
}


As I see no similar solution inside NewPing, I think you could include it in next NewPing release, if you want to. And adding an explicit reference to this issue, and how to fix it by setting "Unlock=true".

NewPing uses all port registers so that inside the library wouldn't be correct.  But, anyone could easily add the code I provided outside the library in their sketch.  Basically use NewPing as normal, but test for an invalid state and cycle the sensor (either by just cycling the power to the sensor or using the above method).

Doing it inside NewPing poses a few problems.  First, in the attempt to be as fast and small as possible, adding additional code for broken sensors seems a bit unwarranted. Also, as NewPing has methods which create event-driven pings, having something that breaks that for 100ms would also break your sketch or the ping polling process if multiple sensors are being pinged.  This would require the user to add additional code to their sketch to deal with this situation.

Instead, it seems more logical for the user to simply add a couple lines of code in their sketch if they happen to have a defective sensor and don't want to get a replacement.  Code in their sketch would be required anyway if they were polling multiple sensors in the background as I would *hightly* suggest anyway.

Then there's the problem of not having a defective sensor to be able to test any type of possible modification to the library.  Just dropping in some code that's not tested doesn't sound like the best idea.  Especially when using the ping_timer() method and associated sketches for multiple sensors in the background.

Anyway, here's what I would suggest doing for those that have a defective sensor and are using NewPing:

Code: [Select]
#include <NewPing.h>

#define TRIGGER_PIN  12  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     11  // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

void setup() {
  Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
}

void loop() {
  delay(50);                     // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
  unsigned int cm = sonar.ping_cm();
  Serial.print("Ping: ");
  Serial.print(cm); // Send ping, get distance in cm and print result (0 = outside set distance range)
  Serial.println("cm");

  if (cm == 0 && digitalRead(ECHO_PIN) == LOW) {
    pinMode(ECHO_PIN, OUTPUT);
    digitalWrite(ECHO_PIN, LOW);
    delay(100);
    pinMode(ECHO_PIN, INPUT);   
  }
}


Just use the standard NewPing library as normal, but do a check for a bad state for your defective sensor and do the reset.  If this works, I can add a Wiki page for NewPing for people if they have a defective sensor that just shows a distance of 0 after getting no ping echo.

Again, I can't test this as all of my sensors work.  But, if someone could confirm this works, I'll be more than happy to build a Wiki page devoted to defective sensors.

Tim
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: aisc on Sep 23, 2015, 05:47 am
I have some of these HC-SR04 sensors. They are not all identical.
I actually run them in a sensor off an ATTiny85.

I would like to test for the fault being discussed.
Could someone please:
- post the minimal code that reveals the fault/problem
- describe the setup you are using
- how to check for the error

TIA.
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: teckel on Sep 23, 2015, 11:33 pm
I have some of these HC-SR04 sensors. They are not all identical.
I actually run them in a sensor off an ATTiny85.

I would like to test for the fault being discussed.
Could someone please:
- post the minimal code that reveals the fault/problem
- describe the setup you are using
- how to check for the error

TIA.
Using the NewPing library (https://bitbucket.org/teckel12/arduino-new-ping/wiki/Home) use the following sketch:

Code: [Select]
#include <NewPing.h>
NewPing sonar(11, 12);  // Trigger pin, echo pin.
void setup() {
  Serial.begin(115200);
}
void loop() {
  delay(50);
  Serial.println(sonar.ping_cm());
}


Sensor is connected to power, ground, pin 11 to trigger, and pin 12 to echo.  Monitor the distance measurement via the Serial Monitor in Arduino IDE.

To test for defective sensor, run the above sketch and you should get distance readings.  Then, point it in a direction it won't get an echo (nothing at least 5 meters away).  This will correctly give a zero (0) reading on the serial monitor.  Then, point the sensor back at something close to the sensor.  If the sensor is defective it will continue to report a zero (0) reading no matter where you point the sensor.  A working sensor will show zero (0) when there's no echo, but then show a reading when pointed towards something within close proximity.

I have over a dozen ultrasonic sensors, and all work correctly.  However, others have reported that they have many sensors and all fail using the above test.

Let me know if you have any questions.

Tim
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: docdoc on Sep 24, 2015, 12:23 am
To test for defective sensor, run the above sketch and you should get distance readings.  Then, point it in a direction it won't get an echo (nothing at least 5 meters away).  This will correctly give a zero (0) reading on the serial monitor.  Then, point the sensor back at something close to the sensor.  If the sensor is defective it will continue to report a zero (0) reading no matter where you point the sensor.
Exactly, this is my SR04s behavior. None of them are working, thus becoming almost useless. Unless I try to "recover" that deadlock, by either temporarily "physically" turning off the SR04, or with that software workaround I implemented in my SRF05 library.

By the way tonight I replaced my last SR04 with an SRF05 from one of my projects, so I'll definitely throw that away. I'm gonna buy a couple of SRF05 just to have a spare, I won't buy SR04 anymore,
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: aisc on Sep 24, 2015, 06:55 am
Quote
Sensor is connected to power, ground, pin 11 to trigger, and pin 12 to echo.  Monitor the distance measurement via the Serial Monitor in Arduino IDE.

To test for defective sensor, run the above sketch and you should get distance readings.  Then, point it in a direction it won't get an echo (nothing at least 5 meters away).  This will correctly give a zero (0) reading on the serial monitor.  Then, point the sensor back at something close to the sensor.  If the sensor is defective it will continue to report a zero (0) reading no matter where you point the sensor.  A working sensor will show zero (0) when there's no echo, but then show a reading when pointed towards something within close proximity.

I have over a dozen ultrasonic sensors, and all work correctly.  However, others have reported that they have many sensors and all fail using the above test.

Let me know if you have any questions.

Tim
Thanks for the concise instructions. Now I just have to find somewhere with 5 metres of nothing - a tall order where I am :)
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: aisc on Sep 24, 2015, 12:21 pm
Well of my total of 5 sensors, I have 3 on hand and tested them. None have any problem being pointed to "infinity" (showing 0) then to something within range and displaying the distance.

Guess I must have gotten some from a "good batch" :)

I have saved the sketch as a "testing tool" - handy to have when buying more.
Thanks Tim.
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: SCION06 on Sep 24, 2015, 03:19 pm
Tim I have tried your code with no avail. copied it directly.
Code: [Select]

#include <NewPing.h>

#define TRIGGER_PIN  12  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     11  // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

void setup() {
  Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
}

void loop() {
  delay(50);                     // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
  unsigned int cm = sonar.ping_cm();
  Serial.print("Ping: ");
  Serial.print(cm); // Send ping, get distance in cm and print result (0 = outside set distance range)
  Serial.println("cm");

  if (cm == 0 && digitalRead(ECHO_PIN) == LOW) {
    pinMode(ECHO_PIN, OUTPUT);
    digitalWrite(ECHO_PIN, LOW);
    delay(100);
    pinMode(ECHO_PIN, INPUT);   
  }
}



Once the sensor returns to 0 (no echo) when something is in front of the sensor. it does not reset. Am I missing something?
thank you
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: teckel on Sep 24, 2015, 03:33 pm
Exactly, this is my SR04s behavior. None of them are working, thus becoming almost useless. Unless I try to "recover" that deadlock, by either temporarily "physically" turning off the SR04, or with that software workaround I implemented in my SRF05 library.

By the way tonight I replaced my last SR04 with an SRF05 from one of my projects, so I'll definitely throw that away. I'm gonna buy a couple of SRF05 just to have a spare, I won't buy SR04 anymore,

Could I have one of the defective SR04 sensors?  With it I could test and implement a deadlock recover in the NewPing library.

Also, if you have multiple sensors you're using in the same project, have you considered using the ping_timer() method with NewPing?  It would allow your sketch to never need to wait for the pings to process as it does everything in the background.

Tim
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: teckel on Sep 24, 2015, 03:34 pm
Thanks for the concise instructions. Now I just have to find somewhere with 5 metres of nothing - a tall order where I am :)
Do you have "outside" where you are?  ;)

Tim
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: docdoc on Sep 24, 2015, 03:49 pm
Could I have one of the defective SR04 sensors?
Hm, sorry, I suspect it'd be an expensive test sending it from Italy to the States.. ;) Especially considering italian postal services efficiency.. ;)
Also, if you have multiple sensors you're using in the same project, have you considered using the ping_timer() method with NewPing?
No, I'll give it a try, but I think it won't make any difference because the problem seems to be on hardware side, and I don't have particular delays, the (in)famous "one second timeout", if I set a few milliseconds as a timeout (e.g. 50.000).

Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: docdoc on Sep 24, 2015, 03:54 pm
Once the sensor returns to 0 (no echo) when something is in front of the sensor. it does not reset. Am I missing something?
I think you should change the "if" Tim wrote.
When SR04 lis in deadlock, the Echo pin is stuck in HIGH state (that's why you get 0ms of high state delay!) so change it to:

Code: [Select]
  if (cm == 0 && digitalRead(ECHO_PIN) == HIGH) {
    pinMode(ECHO_PIN, OUTPUT);
    digitalWrite(ECHO_PIN, LOW);
    delay(100);
    pinMode(ECHO_PIN, INPUT);   
  }
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: aisc on Sep 24, 2015, 04:52 pm
Do you have "outside" where you are?  ;)

Tim
Lol - That was the plan, see reply #36.
Since my laptop's battery is shot, setting up outside with no nearby power source or extension lead was going to be a pain. Anyway the 8th floor window proved ideal.
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: SCION06 on Sep 24, 2015, 05:16 pm
I think you should change the "if" Tim wrote.
When SR04 lis in deadlock, the Echo pin is stuck in HIGH state (that's why you get 0ms of high state delay!) so change it to:

Code: [Select]
  if (cm == 0 && digitalRead(ECHO_PIN) == HIGH) {
    pinMode(ECHO_PIN, OUTPUT);
    digitalWrite(ECHO_PIN, LOW);
    delay(100);
    pinMode(ECHO_PIN, INPUT);   
  }

Changed as you had suggested docdoc, But now it gives me very large numbers like in the hundreds when it is very close to my hand. I will go over my pins and make sure they are all correct. But that LOW to HIGH change worked.
Thank you.
Note, I am just testing singular sensors as I recently got some in the mail and just want them to work before I put them into a project.
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: docdoc on Sep 24, 2015, 05:35 pm
Changed as you had suggested docdoc, But now it gives me very large numbers like in the hundreds when it is very close to my hand.
Hm, what exactly gives you such large numbers? If it's the "cm" variable there's something wrong. If not, tell us where you read that (if you read hundreds, it'd be some time measure in microseconds?).
Quote
But that LOW to HIGH change worked. Thank you.
Good.
Quote
Note, I am just testing singular sensors as I recently got some in the mail and just want them to work before I put them into a project.
Hope you succeed, otherwise replace "put them into a project" with "throw them in a waste bin". :D And buy SRF05.
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: docdoc on Sep 24, 2015, 05:46 pm
Since my laptop's battery is shot,
No, please don't shoot your laptop! :D :D
Anyway the 8th floor window proved ideal.
Seriously, such sensor can't reliably measure distances greater than a few metres (3 or 4 mt), any attempt to detect longer distance measures will give you high uncertain data due to increasing sound front width, reflexions, mixed obstacles, alignment of the obstacles (a glass surface at 45 degrees will give you no echo at all), and other technical issues like the power of the transmitter and the receiver sensitivity. For a very cheap SR04 all those things come in great consideration!
Btw, if you set the timeout to smaller values than 1.000.000 (1 sec) like 50.000 (50 ms) and don't live in a japanese-style capsule room, you have enough space to test with :D
You can have the same effect by completely covering the sensor with your hand, as this blocks any possible echo to get back to sensor.
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: SCION06 on Sep 24, 2015, 06:12 pm
Hm, what exactly gives you such large numbers? If it's the "cm" variable there's something wrong. If not, tell us where you read that (if you read hundreds, it'd be some time measure in microseconds?).Good.Hope you succeed, otherwise replace "put them into a project" with "throw them in a waste bin". :D And buy SRF05.

I am reading this is the serial monitor. The idea that it's in microseconds makes sense, looking at the original NewPing example and the timeout fix the math has been removed to convert microseconds to cm. Thats what i see I do not know the math guess thats next to work out
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: teckel on Sep 24, 2015, 07:02 pm
I am reading this is the serial monitor. The idea that it's in microseconds makes sense, looking at the original NewPing example and the timeout fix the math has been removed to convert microseconds to cm. Thats what i see I do not know the math guess thats next to work out

ping_cm() does the ping and converts the distance to CM automatically.  To get the reading in milliseconds, you would use the ping() method.

Also, if your sensors are proven to be defective, instead of throwing them away, send them my way.  I really need a defective one to correctly reprogram NewPing to work with these sensors.

Tim
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: SCION06 on Sep 24, 2015, 07:07 pm
Well today is the slowest day at work so I have been able to work on this.  NewPing code with reset that is working for me know,
Code: [Select]
// ---------------------------------------------------------------------------
// Example NewPing library sketch that does a ping about 20 times per second.
// ---------------------------------------------------------------------------

#include <NewPing.h>

#define TRIGGER_PIN  12  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     11  // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

void setup() {
  Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
}

void loop() {
  delay(50);                      // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
  unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds (uS).
 
  Serial.print("Ping: ");
  Serial.print(sonar.convert_cm(uS)); // Convert ping time to distance in cm and print result (0 = outside set distance range)
  Serial.println("cm");


if (uS == 0 && digitalRead(ECHO_PIN) == HIGH) {
    pinMode(ECHO_PIN, OUTPUT);
    digitalWrite(ECHO_PIN, LOW);
    delay(100);
    pinMode(ECHO_PIN, INPUT);   
  }
}

Notice the convert.sonar_cm line this was missing so my serial monitor (as docdoc suggested) only showing in microseconds. After some digging and returning to the library home page found some command lines I did not know about.
Thank you to those who helped and those who provided the library.
Tim I saw your post after I had posted this, let me know what you think. Readings on the serial monitor are correct now. My sensors are a buy from ebay as well, and work until they do not recieve a ping. With this reset in the program they are working.
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: teckel on Sep 25, 2015, 11:13 pm
Well today is the slowest day at work so I have been able to work on this.  NewPing code with reset that is working for me know,
Code: [Select]
// ---------------------------------------------------------------------------
// Example NewPing library sketch that does a ping about 20 times per second.
// ---------------------------------------------------------------------------

#include <NewPing.h>

#define TRIGGER_PIN  12  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     11  // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

void setup() {
  Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
}

void loop() {
  delay(50);                      // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
  unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds (uS).
 
  Serial.print("Ping: ");
  Serial.print(sonar.convert_cm(uS)); // Convert ping time to distance in cm and print result (0 = outside set distance range)
  Serial.println("cm");


if (uS == 0 && digitalRead(ECHO_PIN) == HIGH) {
    pinMode(ECHO_PIN, OUTPUT);
    digitalWrite(ECHO_PIN, LOW);
    delay(100);
    pinMode(ECHO_PIN, INPUT);   
  }
}

Notice the convert.sonar_cm line this was missing so my serial monitor (as docdoc suggested) only showing in microseconds. After some digging and returning to the library home page found some command lines I did not know about.
Thank you to those who helped and those who provided the library.
Tim I saw your post after I had posted this, let me know what you think. Readings on the serial monitor are correct now. My sensors are a buy from ebay as well, and work until they do not recieve a ping. With this reset in the program they are working.
You could also just use the  sonar.ping_cm() method.  In other words just do something like this:

Code: [Select]
unsigned int cm = sonar.ping_cm();
...
Serial.print(cm);


I'd love to have a sensor that doesn't work, all of my work all the time, even when pointed to infinity.

Tim
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: mzbas on Nov 22, 2015, 04:57 pm
the solution to the sensor being stuck at zero is in this link. its the 2. post, by docdoc. You will need the NewPing library which is far better.

A working code:

#include <NewPing.h>

#define TRIGGER_PIN 12

#define ECHO_PIN 11

#define MAX_DISTANCE 200

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

void setup() {

Serial.begin(9600);

}

void loop() {

delay(50);

unsigned int uS = sonar.ping();

pinMode(ECHO_PIN,OUTPUT);

digitalWrite(ECHO_PIN,LOW);

pinMode(ECHO_PIN,INPUT);

Serial.print("Ping: ");

Serial.print(uS / US_ROUNDTRIP_CM);

Serial.println("cm");

}

link: http://forum.arduino.cc/index.php?topic=55119.15

NewPing link: http://playground.arduino.cc/Code/NewPing´╗┐
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: dilettant on Dec 06, 2015, 11:09 pm
Hi.

Recently I have bought 3 SR04 sensors from one vendor in China, all of them have the mentioned bug. Thanks Tim "teckel" & Alex "docdoc" for solution in post #41.

I will buy SRF05 for my future robot vacuum cleaner, but thank you for temporary solution. I won time to play with my robo-car until new sensors arrive!

boris.
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: dilettant on Dec 08, 2015, 12:04 am
My joy was premature..

This SR04 sensor gets in HIGH state so frequently and so fast. Even if I introduce the above mentioned code to reset the ECHO_PIN
and place the next command to update the distance to obstacle and the next to print the state of the ECHO_PIN it becomes stack every several seconds!

It looks like fighting with this sensor is impossible.

if (distance == 0 && digitalRead(ECHO_PIN) == HIGH) // reset the defective SR04 sensor
  {
    pinMode(ECHO_PIN, OUTPUT);
    digitalWrite(ECHO_PIN, LOW);
    delay(100);
    pinMode(ECHO_PIN, INPUT); 
    distance = sonar.ping_cm();
  }
if(digitalRead(ECHO_PIN) == HIGH && distance == 0)
  {Serial.println("ECHO_PIN reset needed");
  }

P.S. Tim, I won't send you those sensors to USA.  :smiley-confuse:
boris.
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: macmac on Jan 03, 2016, 02:19 pm
I apologize for my English but use google translator. I saw that the sensor SR04, when he goes to 0, does not return to mark correct values unless power is removed or snapped his fingers in front of it ... Why is "reset" when they hear a noise?
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: mikb55 on Jan 03, 2016, 03:46 pm
I apologize for my English but use google translator. I saw that the sensor SR04, when he goes to 0, does not return to mark correct values unless power is removed or snapped his fingers in front of it ... Why is "reset" when they hear a noise?

Presumably the sound of snapping fingers contains enough ultrasonic sound to trigger the receive circuit of sensor in the absence of a reflected pulse.
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: macmac on Jan 03, 2016, 08:18 pm
So it should not be a problem of the receiver. How can you do to send a new signal in the event of output = 0?
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: mikb55 on Jan 04, 2016, 12:34 am
So it should not be a problem of the receiver. How can you do to send a new signal in the event of output = 0?

Cycle the power. This always works.
Read earlier posts to see a possible software workaround. It may work for some modules, but not for others.
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: knut_ny on Jan 12, 2016, 11:01 pm
I have 2 different lots og SR04.   Five of them with a 4MHz x-tal the others with 8MHz x-tals.
ALL work perfect when uno has USB power (ca. 4.85V), but all with the 4MHz xtal fails as soon as I connect an additional external power (battery 8.4V)  Arduino voltage is then almost perfect 5V.

Have someone else experienced such behavior ?..  and is there a simple cure other than ideas already mentioned
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: Murray_C on Jan 14, 2016, 05:20 pm
I'd love to have a sensor that doesn't work, all of my work all the time, even when pointed to infinity.

Tim
The code you posted for the bug fix works fine after changing the "if" statement to

if (cm == 0 && digitalRead(ECHO_PIN) == HIGH)

Both of the sensors I purchased have the "lock" problem.  Thanks to you and Alex for  providing a workable solution.

While I don't have a spare sensor to send, here is the one I have

http://www.amazon.ca/gp/product/B00F167T2A?psc=1&redirect=true&ref_=oh_aui_detailpage_o06_s00 (http://www.amazon.ca/gp/product/B00F167T2A?psc=1&redirect=true&ref_=oh_aui_detailpage_o06_s00)
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: vgtlcs on Jan 25, 2016, 06:19 am
Guys - I hate to be the bearer of a blinding flash of reality but NONE of your suggestions actually work for the HC-SR04 as claimed, be it either " add these lines after this line, or use New Ping, or what ever - all i ever get is the correct reading on opening the monitor which then returns incessant "0" thereafter until a restart - then the same process repeats!!! I do feel certain I will receive a fair smattering of "oh you must have a faulty unit" - which of course is plausible but there must be one hell of a lot of faulty units doing the rounds globally given the weight of people like myself who have raised this ongoing issue and then given up by bashing our collective heads against the wall!!!  I just wish you guys offering suggestions would include the complete code and how you are wiring it up etc etc as it is madeningly frustrating as a newby to follow all the "expert offers of how this works etc", only to find after wasting numerous hours that it simply doesn't!

Please don't get me wrong I am extremely appreciative of the efforts most of you guys go to help us 'not so experienced arduino users' out!

The one thing I haven't yet tried was docdoc's (?) suggestion of using the SR05 code and library then uncommenting the SR04 lock line of code - I would have done this except that I could not get a download of the SR05 library anywhere - at least one that only seemed a few years old at the latest!! But would this really work when using an SR04 unit???

Any helpful comments on trying to resolve this SR04 dilemma would be extremely well received by myself. Unfortunately I only have the SR04 units and do plan on buying the SR05's - but if I do do this - will I simply jumping from the frying pan into the fire????? can any of you guys offer reassurance that the SR05 does not suffer from similar problems the SR04 does? Cheers
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: Freduj on Feb 04, 2016, 05:39 pm

Hello everyone
I'm in the same case as you, 3 sensors and all the same problems .
even the solution with transistor to turn off the power does nothing.
a lot of research and time spent, but no real solution ,
TECKEL , have you received a defective sensor?
Thank you for your help.
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: vidal_g on Feb 10, 2016, 06:40 pm
Howdy arduiners?

After being very upset with this SR-04 meter, I have found that works for my models. Here it goes.

The solution consists in giving power to the SR-04 through a transistor, a BC-547. The SR-04 is the load, and the transistor is activated with one output pin of the arduino. Newping library is used and code in explained below. Basically consist in checking if the distances is getting too low and, in this case, power down the meter, delay and then power it up again. Also a led has been added to test the condition of the power. When lit the SR-04 is powered up.

It FINALLY worked for me! If it is not clear enough I can send anyone a draft schematic or even a picture of the mosnter. Hope anyone can breath again now! ;-)

-------------------------------------------------------


#include <NewPing.h>

/*-----( Declare Constants and Pin Numbers )-----*/
#define  TRIGGER_PIN  8
#define  ECHO_PIN     9
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters).
                         //Maximum sensor distance is rated at 400-500cm.
/*-----( Declare objects )-----*/
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
/*-----( Declare Variables )-----*/
int DistanceIn;
int DistanceCm;
const int resetsensor = 12; //Pin to BC-547 in Common Emitter mode thru 1k ohm resistor in base
const int ledsensor= 13; //Light to clone the reset sensor

void setup()   /****** SETUP: RUNS ONCE ******/
{
  Serial.begin(9600);
  Serial.println("Resetting the dammed SR-04 UltraSonic Distance Meter");
  Serial.println("questions to vidalgm@gmail.com");
  pinMode (resetsensor, OUTPUT);
  pinMode (ledsensor, OUTPUT);
 
}//--(end setup )---


void loop()   /****** LOOP: RUNS CONSTANTLY ******/
{
  digitalWrite (resetsensor,HIGH); //Gives power to the dammned SR-04 thru the BC-547
  delay(100);// Wait 100ms between pings (about 10 pings/sec). 29ms should be the shortest delay between pings.
  DistanceIn = sonar.ping_in();
  Serial.print("Ping: ");
  Serial.print(DistanceIn); // Convert ping time to distance and print result
                            // (0 = outside set distance range, no ping echo)
  Serial.print(" in     ");
 
  delay(100);// Wait 100ms between pings (about 10 pings/sec). 29ms should be the shortest delay between pings.
  DistanceCm = sonar.ping_cm();
  Serial.print("Ping: ");
  Serial.print(DistanceCm);
  Serial.println(" cm");
  if (DistanceCm < 5){  //If distance is getting too low
  digitalWrite (resetsensor, LOW); //reset transistor, this is, take out power of SR-04
  digitalWrite (ledsensor, LOW); //light down to indicate we are resetting
  delay (200);
  digitalWrite (resetsensor, HIGH); //power up SR-04 again
  digitalWrite (ledsensor, HIGH); //ligh up to indicate SR-04 is again powered up
  }

}//--(end main loop )---

/*-----( Declare User-written Functions )-----*/

// None
//*********( THE END )***********
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: cspiel on Feb 26, 2016, 05:46 pm
The solution of vasimv in post #13 works perfectly. I tried it.

Diode between trigger and C9. No extra gpio, no transistor for power off/on needed.
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: terennum on Apr 15, 2016, 03:20 am
Could you please share the transistor wiring diagram? I have not been able to pull the output down to 0V with a pulldown resistor.

Howdy arduiners?

After being very upset with this SR-04 meter, I have found that works for my models. Here it goes.

The solution consists in giving power to the SR-04 through a transistor, a BC-547. The SR-04 is the load, and the transistor is activated with one output pin of the arduino. Newping library is used and code in explained below. Basically consist in checking if the distances is getting too low and, in this case, power down the meter, delay and then power it up again. Also a led has been added to test the condition of the power. When lit the SR-04 is powered up.

It FINALLY worked for me! If it is not clear enough I can send anyone a draft schematic or even a picture of the mosnter. Hope anyone can breath again now! ;-)

-------------------------------------------------------


#include <NewPing.h>

/*-----( Declare Constants and Pin Numbers )-----*/
#define  TRIGGER_PIN  8
#define  ECHO_PIN     9
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters).
                         //Maximum sensor distance is rated at 400-500cm.
/*-----( Declare objects )-----*/
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
/*-----( Declare Variables )-----*/
int DistanceIn;
int DistanceCm;
const int resetsensor = 12; //Pin to BC-547 in Common Emitter mode thru 1k ohm resistor in base
const int ledsensor= 13; //Light to clone the reset sensor

void setup()   /****** SETUP: RUNS ONCE ******/
{
  Serial.begin(9600);
  Serial.println("Resetting the dammed SR-04 UltraSonic Distance Meter");
  Serial.println("questions to vidalgm@gmail.com");
  pinMode (resetsensor, OUTPUT);
  pinMode (ledsensor, OUTPUT);
 
}//--(end setup )---


void loop()   /****** LOOP: RUNS CONSTANTLY ******/
{
  digitalWrite (resetsensor,HIGH); //Gives power to the dammned SR-04 thru the BC-547
  delay(100);// Wait 100ms between pings (about 10 pings/sec). 29ms should be the shortest delay between pings.
  DistanceIn = sonar.ping_in();
  Serial.print("Ping: ");
  Serial.print(DistanceIn); // Convert ping time to distance and print result
                            // (0 = outside set distance range, no ping echo)
  Serial.print(" in     ");
 
  delay(100);// Wait 100ms between pings (about 10 pings/sec). 29ms should be the shortest delay between pings.
  DistanceCm = sonar.ping_cm();
  Serial.print("Ping: ");
  Serial.print(DistanceCm);
  Serial.println(" cm");
  if (DistanceCm < 5){  //If distance is getting too low
  digitalWrite (resetsensor, LOW); //reset transistor, this is, take out power of SR-04
  digitalWrite (ledsensor, LOW); //light down to indicate we are resetting
  delay (200);
  digitalWrite (resetsensor, HIGH); //power up SR-04 again
  digitalWrite (ledsensor, HIGH); //ligh up to indicate SR-04 is again powered up
  }

}//--(end main loop )---

/*-----( Declare User-written Functions )-----*/

// None
//*********( THE END )***********
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: vidal_g on Apr 22, 2016, 10:59 am
If any of you want a draft of the circuit, please email me since I cannot post here a graphic.
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: AWOL on Apr 22, 2016, 11:27 am
If any of you want a draft of the circuit, please email me since I cannot post here a graphic.
You could attach it.
Title: A working circuit with a transistor reset
Post by: vidal_g on Apr 28, 2016, 01:01 am
Related to my previous post (now I know how to attach an image)

Enjoy
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: ScottC on Aug 03, 2016, 05:36 am
I have an HC-SR04 module that works well - without issues, and have just received the aforementioned cheap eBay alternative which hangs/timeout. I have attached a picture for comparison.

Hope this helps someone out there who is trying to identify if their module is in "crappy" category.

The one on the left is the one that works well.
The one on the right is the crappy version from eBay.

Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: vidal_g on Aug 25, 2016, 12:37 am
Thanks a lot, ScottC. I do have a couple of crappy units very alike to yours, though not really "equal". I also bought a couple of HC-SRO5 that seems to work as they have.
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: nedstar on Oct 10, 2016, 06:45 pm
I have also alway's this problem with the HC-SR04 until I find out that on the backside board of the HC-SR04 is a possibility to make a reset with a 1k resistor, this works very stable.
I create all kind of errors with the sensor try to let it crash, but now it keep recover itself and runs all the time fine. Try the code below to test;

/* Ping))) Sensor
    The circuit:
   * Vcc of the Sensor attached to +5V
   * GND of the Sensor attached to ground
   * Trigger and Echo of the Sensor together attached to digital pin 7
 */
const int pingPin = 7;   // Digital Pin 7 on Arduino
const int ResetPin = 8; // Digital Pin 8 on Arduino, I use as Reset

void setup() {
  Serial.begin(9600);
  pinMode(pingPin, OUTPUT);
 
  pinMode(ResetPin, OUTPUT);
  digitalWrite(ResetPin, LOW);
}

void loop() {
  long duration, inches, cm;// The distance result in inches and centimeters:

  // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);

  // The same pin is used to read the signal from the PING))): a HIGH
  // pulse whose duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);

  // convert the time into a distance
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);

  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();

  delay(100);
 
if (cm <1) //************ Reset Sensor ************
  {
  digitalWrite(ResetPin, HIGH);
  delay(2);
  digitalWrite(ResetPin, LOW);
  Serial.println("********** Reset Sensor **********");
  }
}

long microsecondsToInches(long microseconds) {
  // According to Parallax's datasheet for the PING))), there are
  // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
  // second).  This gives the distance travelled by the ping, outbound
  // and return, so we divide by 2 to get the distance of the obstacle.
  // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
  return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds) {
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  // The ping travels out and back, so to find the distance of the
  // object we take half of the distance travelled.
  return microseconds / 29 / 2;
}


Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: DaveEvans on Oct 10, 2016, 07:39 pm
The image in post 67, showing "good" and "crappy" sensors...not verified by me...I'm just showing the pic so you don't have to click on the link...

(https://forum.arduino.cc/index.php?action=dlattach;topic=55119.0;attach=183338)
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: 6v6gt on Oct 21, 2016, 08:16 am
Interestingly, I have just received two HC-SR04 sensors from http://www.banggood.com/Wholesale-Ultrasonic-Module-HC-SR04-Distance-Measuring-Ranging-Transducer-Sensor-p-40313.html (http://www.banggood.com/Wholesale-Ultrasonic-Module-HC-SR04-Distance-Measuring-Ranging-Transducer-Sensor-p-40313.html) These appear to be of "Not good" variety mentioned in the previous post with the tiny "J1" mark to the right of the terminal block and other identifying characteristics.

Indeed, when I tried these with the sample code on the Sparkfun Site linked from "example code" on this page https://www.sparkfun.com/products/13959 (https://www.sparkfun.com/products/13959) I got the typical freeze problem  due to the missing timeouts.

However, I was able to solve the problem purely by hacking the sketch to add my own timeouts and the devices work perfectly with it. There was no need for any of the "hardware" tricks mentioned in this thread.

There is probably a large number of slightly different HC-SR04 designs, all exhibiting different behaviour.

Anyway, here is the adapted code which works for exactly the devices I have just acquired:

Code: [Select]

/**
 * ex. sparkFun
 *
 * mod  20.10.2016 timeouts on waits
 *
 *
 * HC-SR04 Demo  
 * Demonstration of the HC-SR04 Ultrasonic Sensor
 * Date: August 3, 2016
 *
 * Description:
 *  Connect the ultrasonic sensor to the Arduino as per the
 *  hardware connections below. Run the sketch and open a serial
 *  monitor. The distance read from the sensor will be displayed
 *  in centimeters and inches.
 *
 * Hardware Connections:
 *  Arduino | HC-SR04
 *  -------------------
 *    5V    |   VCC    
 *    7     |   Trig    
 *    8     |   Echo    
 *    GND   |   GND
 *  
 * License:
 *  Public Domain
 */

// Pins
const int TRIG_PIN = 7;
const int ECHO_PIN = 8;

// Anything over 400 cm (23200 us pulse) is "out of range"
const unsigned int MAX_DIST = 23200;

void setup() {

  // The Trigger pin will tell the sensor to range find
  pinMode(TRIG_PIN, OUTPUT);
  digitalWrite(TRIG_PIN, LOW);

  // We'll use the serial monitor to view the sensor output
  Serial.begin(9600);
}

void loop() {

  unsigned long t1;
  unsigned long t2;
  unsigned long pulse_width;
  float cm;
  float inches;

  // Hold the trigger pin high for at least 10 us
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  // Wait for pulse on echo pin

  unsigned long wait1 = micros();
  while ( digitalRead(ECHO_PIN) == 0  ) {
    if ( micros() - wait1 > MAX_DIST ) {
        Serial.println("wait1 Out of range");
        return ;
    }
  }

  // Measure how long the echo pin was held high (pulse width)
  // Note: the micros() counter will overflow after ~70 min
  t1 = micros();
    while ( digitalRead(ECHO_PIN) == 1  ) {
    if ( micros() - t1 > MAX_DIST ) {
        Serial.println("wait2 Out of range");
        return ;
    }
  }
  
  t2 = micros();
  pulse_width = t2 - t1;

  // Calculate distance in centimeters and inches. The constants
  // are found in the datasheet, and calculated from the assumed speed
  //of sound in air at sea level (~340 m/s).
  cm = pulse_width / 58.0;
  inches = pulse_width / 148.0;

  // Print out results
  if ( pulse_width > MAX_DIST ) {
    Serial.println("Out of range");
  } else {
    Serial.print(cm);
    Serial.print(" cm \t");
    Serial.print(inches);
    Serial.println(" in");
  }
  
  // Wait at least 60ms before next measurement
  delay(60);
}


Incidentally, the finish on the devices is not too good. They have obviously added the transducers after washing the board, but then not cleaned away the flux from the transducer solder joints, leaving large white powdery deposits. But for the price I paid, I will not complain too loudly.

The device is quite susceptible to electrical noise and needs a capacitor (say 100 uF) across the supply terminals.
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: kmckee8372 on Dec 27, 2016, 04:25 am
Some knock-off models of the HC-SR04 do not implement a timeout if no echo is detected at all.  In that case, the echo pin will simply remain high forever and will not generate any new pings, regardless of what you do with the trigger pin.  The original model from Robot Electronics (http://www.robot-electronics.co.uk/htm/srf04tech.htm) times out after 36 ms and does not have this problem, but many (all?) cheap knock-off models do.

You can reproduce the problem easily by covering the receiver transducer with your thumb, then removing your thumb.  If your sensor doesn't have a timeout, it will stop generating pings and the only way to recover is to power cycle the sensor.

A workaround that works for me so far is to test the state of the echo pin 100 ms after triggering a ping.  If it's still high, you're in a stuck state.  If you wire power to the sensor through a transistor and control that transistor via another pin, then you can power cycle the sensor via software and get back to a working state.
I was banging my head against this for quite some time until I found this.  I tried your suggestion to power cycle it and it's got me up and running.  Thank you!
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: rhauff on Jan 09, 2017, 09:14 pm
The idea of powering the HC-SR04 from an Arduino output is working perfectly for me.

I used Tim's code from post #31, modified with with DocDoc's correction on the "If" (change "LOW" to "HIGH")

and refinements for my particular sensors.  The following code adds only 110 mS for a power reset on the sensor when an out of range is detected.

Notice, inside the IF loop, the section "delay(60);   sonar.ping_cm();" may be deleted if your sensors do not return false echo after reset.  I have 2 that do not need it.  Total time added for reset is then only 50 mS.

Code: [Select]

#include <NewPing.h>

#define TRIGGER_PIN  2  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     3  // Arduino pin tied to echo pin on the ultrasonic sensor.
#define USPOWER_PIN  4
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

void setup() {
  Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
  pinMode(USPOWER_PIN, OUTPUT);
  digitalWrite(USPOWER_PIN, HIGH);
}

void loop() {
  unsigned int cm = sonar.ping_cm();
  Serial.print("Ping: ");
  Serial.print(cm); // Send ping, get distance in cm and print result (0 = outside set distance range)
  Serial.println("cm");
  delay(30);                     // Wait 30ms between pings (about 30 pings/sec). 29ms should be the                                // shortest delay between pings.
 
  if (cm == 0 && digitalRead(ECHO_PIN) == HIGH) {
    digitalWrite(USPOWER_PIN, LOW);
    delay(50);                // 50 mS is the minimum Off time to get clean restart
    digitalWrite(USPOWER_PIN, HIGH); // Adjust this value if your sensors don't read after reset
    delay(60);                // Some sensors throw out a very short false echo after timeout
    sonar.ping_cm();       // 5cm-10cm value.  If your sensors do not throw out
                                  // this false echo, you can get rid of this delay and ping after power HIGH
  }                              // Conversely, if you still get a false echo, you may need to increase
}                                // the delay.




Good Luck!
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: jjvbbvjj on Jan 13, 2017, 06:47 pm
Alex "docdoc",

Your SRF05 lib worked on my SR04 sensor with the lockup on zero output when out of range.  Works perfectly now.  Thanks.

John
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: arielnh56 on Feb 26, 2017, 06:55 am
I ran into this today while putting together a blog video for how to daisy-chain my little octosonar board to drive 12 of these little buggers with my sonari2c library (apologies for the plug).

I prototyped all this using SR04s I bought last year from somewhere in China (not banggood - it's not in my purchase history there) and it all works just dandy. Those units don't look like either of the ones pictured above.

The new ones I *did* get from Bangood recently and look like the "bad" ones above (same circuit, narrow silk screen) and my tests/demos were locking up occasionall (I was blaming it on wiring). I finally got to the bottom of this today (reproduce 100% by putting thumb over sensor) and google found this thread.

The most obvious difference between my "good" ones and the "bad" ones is the "bad' ones have 10K pullup resistors on Trig and Echo. My "good" ones do not - very high resistance between Trig, Echo and Vcc,Gnd.

The "good" and "bad" ones above both seem to have the pullups (R1/R2) so they are clones. Sometimes clones have different component values due to the cloners not being as good as the dudes on Kamino.

I tried tying the Echo to ground - seemed to clear it, but I can't do that through my board, nor can I flap the power.

While debugging I connected echo to the LED on my protoshield so I'd have a visual indicator. Bingo. Problem cleared right up. The protoshield has an inline resistor with the LED, but I figured these pulses are short, so how about just connecting a LED directly across Trig and GND. Seems to work....

Can someone else try this and verify?

Also can the guy with the good and bad clones check the resistance on r1/r2 on the "good" ones? I suspect they may be more than 10k i.e. weaker.

Update: I tried a variety of LEDs direct connect and they did not all work. The little red ones with 1.6V forward voltage did not lock up my board, but did not give a signal back from the rogue sensor either - probably pulling the voltage too low for the logic gate.

The rest seem to be 2V forward voltage and work direct without a resistor. All the LEDs fix the issues with a 220 ohm series resistor.

I was thinking of putting blinky activity LEDs on the next version of my board anyway, I think this clinches it.

Why does this work? No idea.
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: arielnh56 on Feb 26, 2017, 07:06 am
I take it back about the clone thing and cheaper components. A closer squint at the picture DaveEvans posted on Oct 10 tells me these are a clone with fewer components. The overall circuit layout looks almost identical, but there are a lot less capacitors.

Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: jlmyra on Feb 26, 2017, 09:34 pm
Is that an LED and resistor on each sensor?
Thanks.
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: arielnh56 on Feb 26, 2017, 11:09 pm
yes, attached between the sensor echo and ground. I just tried a 1k resistor (no LED) and that worked too.

Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: arielnh56 on Feb 26, 2017, 11:14 pm
It occurs to me that those 10K pullups may be supposed to be 10k pull-downs. I got some protoshields last month that had one of the tracks mis-designed and connected Vcc direct to Groun, so dumbassity like this definitely happens in the knock-off world.

If someone could check that on the "good" ones it might explain a lot.
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: vasimv on Apr 04, 2017, 04:01 am
How to solder diode to prevent locking problem. Almost any diode will go (no need such big one, i just didn't have other in my inventory).
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: kanwarkumar on Jan 19, 2018, 12:56 am
How can I Stop the measurement of ultrasonic sensor.... during program ruining.....please help me
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: arielnh56 on Mar 23, 2018, 04:50 am
I was updating my tindie text for these sensors and came back here and realized I had never come back and listed the solution found to this issue.

My sincere apologies. Open source is give and take, not just take.

many thanks to @jlmyra above for figuring out the actual cause - and persuading me by this action to buy an oscilloscope. http://www.bitscope.com/product/BS05/

The bad sensors raise the echo pin when they don't get a response. They never time out. Period. In brief: avoid.

They do reset the echo when a new cycle is started, so they are not a completely lost cause, once their behavior is understood.

The data sheets say that the timeout from no response is 37ms. While this may have been true for the original HC-SR04, the observed value for the not-bad clones is between 150ms and 200ms. So even with the "good" sensors my original octosonar board was getting interference between adjacent sensors when there was no echo as that sensor would still be hanging up the pin when the next one came active after the 50ms rotation period. This was patched in software to force a wait until the pin dropped.

The revised version of my "OctoSonar" board uses tri-state buffers to isolate the echoes from each other entirely and enforces a sensible 50ms (software changeable) time window to each sensor, eliminating the lockups and delays above, regardless of whether the sensor is one of the "good" or "bad" ones.

The "good" sensors I use have a different board layout from either of the ones shown in port #70. They are distinguished by having the passive components arrranged in two vertical rows.

(https://cdn.tindiemedia.com/images/resize/wY7lQFVt3ObxzjAuBcvY6fNVm6Q=/p/fit-in/653x435/filters:fill(fff)/i/91176/products/2017-06-17T07%3A32%3A10.779Z-hc-sr04-back.png)
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: jaknil on Sep 01, 2018, 10:13 pm
(New poster.)
I got my super cheap HC-SR04 sensors working with a software only solution after they all experienced the same error of getting stuck waiting for lost echos.

I have modifed the arduino Examples -> Sensors -> Ping code for the Ping Ultrasonic Range Finder (https://www.arduino.cc/en/Tutorial/Ping) and explained all steps in comments.

I hope this will be of help for others that come looking for a software only solution.  (Based on docdoc's solution in reply #16)

Code: [Select]

/*
 Ultrasonic distance sensor

 This sketch reads a ultrasonic rangefinder and returns the distance
 to the closest object in range. To initiate a reading it sends out a
 sound pulse and then listens for the echo of the pulse to return.
 The time it takes before the echo is registered is proportional to
 the distance of the object from the sensor.

 The circuit:
- +V connection of the Sensor attached to +5V
- GND connection of the Sensor attached to ground
- SIG connection of the Sensor  attached to digital pin 7 (TRIG and ECHO can be combined)


 created 3 Nov 2008
 by David A. Mellis
 modified 30 Aug 2011
 by Tom Igoe
 modified 1 Sept 2018
 by Jakob Nilsson
 
 This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/Ping
*/

// This constant won't change. It's the arduino pin that communicates with the sensor:
const int pingPin = 7;

// We need to add a timeout for the longes range that the Sensor can sense, so that
// it does not get stuck waiting for an echo that never comes.
// long timeout = 157 / 74 / 2;//Timeout in microseconds for a max range of 157 inches
const long timeout = 400 * 29 * 2; //Timeout in microseconds for a max range of 400 cm

void setup() {
 // initialize serial communication:
 Serial.begin(9600);
}

void loop() {
 // establish variables for duration of the ping, and the distance result
 // in inches and centimeters:
 long duration, inches, cm, mm;

 // The sensor is triggered by a HIGH signal for 10 microseconds.
 // Give a short LOW pulse beforehand to ensure a clean HIGH pulse and
 // to reset the sensor if it didn't register an echo from the last ping:
 pinMode(pingPin, OUTPUT);
 digitalWrite(pingPin, LOW);
 delayMicroseconds(10); //This delay lets the capacitors empty and resets the sensor
 digitalWrite(pingPin, HIGH);
 delayMicroseconds(10);
 digitalWrite(pingPin, LOW);

 // The same pin is used to read the signal from the Sensor: A HIGH pulse
 // whose duration is the time (in microseconds) from the sending of the ping
 // to the reception of its echo off of an object.
 pinMode(pingPin, INPUT);
 duration = pulseIn(pingPin, HIGH,timeout);

 // convert the time into a distance
 inches = microsecondsToInches(duration);
 cm = microsecondsToCentimeters(duration);
 mm = microsecondsToMillimeters(duration);

 Serial.print(inches);
 Serial.print(" in, ");
 Serial.print(cm);
 Serial.print(" cm, ");
 Serial.print(mm);
 Serial.print(" mm");
 Serial.println();
 
 delay(100); //Recommended minimum cycle time is 50ms so that the echo has time to fade
}

long microsecondsToInches(long microseconds) {
 // According to Parallax's datasheet for the PING))), there are 73.746
 // microseconds per inch (i.e. sound travels at 1130 feet per second).
 // This gives the distance travelled by the ping, outbound and return,
 // so we divide by 2 to get the distance of the obstacle.
 // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
 return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds) {
 // The speed of sound is 343 m/s or 29 microseconds per centimeter.
 // The ping travels out and back, so to find the distance of the object we
 // take half of the distance travelled.
 return microseconds / 29 / 2;
}

long microsecondsToMillimeters(long microseconds) {
 // The speed of sound is 343 m/s or 2.9215 microseconds per millimeter.
 // The ping travels out and back, so to find the distance of the object we
 // take half of the distance travelled.
 return microseconds * 10000 /29215 / 2;
}


Hope it helps!
Title: Re: Ultrasonic distance sensor HC-SR04 lack of timeout problem
Post by: nielyay on Sep 02, 2018, 10:27 am
Hello,
Quote
detect an echo.
This sometimes results in the echo line staying high forever
have you check the connector for the echoPin?

and what is the code that you input to the HC-004.