I recently got an HC-SR04 Ultrasonic sensor, and today I hooked it up. At first it works great, and I am able to get a good distance reading to the serial monitor every 100 ms. But after a while, some weird stuff happens. The transmit LED of the Arduino stops blinking rapidly every 100 ms, but starts blinking slowly every second. Furthermore, whenever the transmit LED blinks, it returns a value of 0.0. When I disconnect the power to the sensor, and reconnect the 5 Volt wire, the sensor works again, returning good values every 100 ms. But after a couple of seconds, the values go back to 0.0 every second.
I think this is happening because the code waits for the echo, and stops waiting after one second. Therefore, when the sensor isn't returning anything, it reduces the frequency to one transmission per second, being 0.0 every time. When I reset the sensor, it starts working again. Does this mean the sensor is broken, or is my code flawed? I think it's unlikely that the sensor is broken, as it is brand new and looks to be in perfect shape.
Thanks in advance!
Code:
void setup() {
pinMode(5,OUTPUT);
pinMode(6,OUTPUT);
pinMode(8,INPUT);
pinMode(9,OUTPUT);
pinMode(10,OUTPUT);
pinMode(11,OUTPUT);
pinMode(13,OUTPUT);
Serial.begin(9600);
}
void loop() {
digitalWrite(9,LOW);
delayMicroseconds(2);
digitalWrite(9,HIGH);
delayMicroseconds(10);
digitalWrite(9,LOW);
long time=pulseIn(8,HIGH);
long distance=(time/2)/29.1;
Serial.println(distance);
delay(100);
}