Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Endless loop if sensor not present/broken/disconnected #3

Open
adrianrolla opened this issue May 5, 2018 · 1 comment
Open

Endless loop if sensor not present/broken/disconnected #3

adrianrolla opened this issue May 5, 2018 · 1 comment

Comments

@adrianrolla
Copy link

Hi Jeremy,
Many thanks for producing this library!
Found a bug, here is the explanation and the fix.

echoInMicroseconds() function has while loops that if sensor is failing / not present / disconnected will never end.

original code within echoInMicroseconds()

    while(digitalRead(_echo) == LOW);

    int pulseStart = micros();

    while(digitalRead(_echo) == HIGH);

fixed code within echoInMicroseconds()

  // sounds go at 350meters/sec, HCSR04 reach is 4mt, to be safe 10mt, at sound speed takes 28 millis 
   const long timeout=100L; // more than safe in normal conditions.
   long started = millis();
   boolean timedout = false;
   while(digitalRead(_echo) == LOW && !(timedout=(millis()-started > timeout)));
   if (timedout) return -1; // negative distance should be treated as error condition.

   int pulseStart = micros();

   started = millis();
   while(digitalRead(_echo) == HIGH && !(timedout=(millis()-started > timeout)));
   if (timedout) return -1; // negative distance should be treated as error condition.

That's all.
Regards

@jeremylindsayni
Copy link
Owner

Brilliant catch - thank you! I'll test this and update the code. I really appreciate you taking the time to identify the issue and write a fix :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants