Hello lovely people of the interwebs,
Head-scratcher for you all: My distance serial readout from my HC-SR04's hang at 0 after working for about 1 min. They read distances perfectly fine then suddenly quit after about 1.5 min and always read 0; it doesn't matter if the object is close or far, static or dynamic. I also switch which pins are being used as trigger and echo on the same rail (Digital 22 to 53) and reuploading the script to no avail.
The only solution I found is unplugging my power source and USB to my computer and restarting the whole program. This is obviously unsustainable.
I have a Arduino Mega 2560 (made in UK) connected to 5 HC-SR04's (made in China). I've only been testing my sensors one at a time. Here is my code; I'm also attaching a picture with the schematic:
//////////////////////////////////////////////////////
// Vcc = 5V
int trigPin = 22;
int echoPin = 23;
long duration, cm, inches;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
// put your main code here, to run repeatedly:
duration = 0;
digitalWrite(trigPin, LOW);
delayMicroseconds(5);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH,20000);
//This is an attempt to get the echoPin to reset
if (duration == 0){
pinMode(echoPin, OUTPUT);
digitalWrite(echoPin, LOW);
delayMicroseconds(200);
pinMode(echoPin, INPUT);
}
cm = (duration/2) / 29.1;
Serial.println(cm);
delay(500);
}
//////////////////////////////////////////////
Troubleshooting methods I've tried:
-
Did you turn it off and turn it back on (computer/Arduino/power source)? Yes. Yes I did

-
Clap my hands. There were forums saying that the sensors could get stuck and a heavy echo event like hand clapping would reset it. Didn't work.
-
TheRandomLab had two solutions here:
TheRandomLab: Repair faulty HC-SR04 ultrasonic sensor (solve erratic no-readings problems)
a. Connect a resistor between the trigger and the reacting pin of the transducer's receiver. Didn't work.
b. Use code to toggle the echo pin from OUTPUT to INPUT then back to OUTPUT. Didn't work. -
Switch pins to different rail (like Digital 2 to 13). Did work temporarily, then fell back to the same problem.
-
Yell at the sensors in frustration. Didn't work.
-
Tap the sensors themselves. Forums were saying that helps the reset process as well. Didn't work.
-
Test to make sure the Arduino rails were actually outputting LOW and HIGH signals in the echo and trigger pins when they're supposed to. This was confirmed using a DMM.
I'm pretty stumped, but the last troubleshooting attempt shows that there's nothing wrong with the Arduino itself, probably the code or the sensors.
If it's the sensors that could be the issue, I'd like to confirm that the code and schematic are okay before I go out and buy some higher quality HC-SR04's.
Thanks all!
