I have some HC-SR04 ultrasonic sensors that I purchased from eBay not long ago. I hooked one up to an Arduino and wrote a quick sketch to test them, and found that none of them work consistently.
It seems that they all stop working when the distance gets too large. I can turn on the Arduino and I hear the sensor clicking while it is pointed at the ceiling ~1.5 meters away. When I turn it towards the other end of the room ~3 meters away, though, the clicking stops and the pulsein() method times out and the distances read 0 cm. Pointing the sensor back at the ceiling does not solve the problem, power must be cycled. I Actually discovered that flicking the sensor can sometimes get it to work again as well, without cycling the power. I searched for people having trouble with the sensor but no one seems to have the problem I am having.
EDIT: I have done some more experimenting and I now think there must not be an internal timeout when a 'click' is sent and not received. The sensor works when aimed at solid surfaces as far as 3 meters away. It stops working in two cases: aimed out a door or aimed at a soft surface. The documentation on the sensor says that it has a range of 4 meters and doesn't work well on soft (sound absorbing) surfaces. My guess is that in these two cases, an echo is not heard at all. The sensor is then stuck waiting for an echo. Flicking it creates the echo it was waiting for and it resumes until another echo is missed.
There are three ICs on the board: an amplifier, a max3232 level shifter, and an unidentifiable one. My guess would be that the third one is some sort of micro controller, so I may try reprogramming or replacing it. Any input on that would be appreciated, though it looks like I answered my own question to the extent possible.
Here is the code I am using. I have triple checked all of the connections and the fact that it works briefly suggests that they are indeed correct.
const int trig = 3;
const int echo = 4;
float elapsed, distance;
void setup() {
pinMode(trig, OUTPUT);
pinMode(echo, INPUT);
Serial.begin(9600);
}
void loop() {
digitalWrite(trig, HIGH);
delayMicroseconds(20);
digitalWrite(trig, LOW);
elapsed = pulseIn(echo, HIGH, 1000000);
// timeout in microseconds
distance = elapsed / 58;
Serial.println((String)(distance) + " cm");
delay(500);
}
pulseIn(pin, value, timeout)
form to specify a maximum time to listen for an echo so your sketch doesn't hang in an out-of-range situation. \$\endgroup\$