I'm currently trying to understand the code that goes with the HC-SR04. I pretty much understand how it works, and why most of the code is written the way it is...but I can't seem to figure out why there is a portion where the trig pin gets set to LOW twice in a row.
for example:
void loop(){
digitalWrite(trigPin, LOW); //Why do we have to start with the trig Pin @ LOW?
delayMicroseconds(2);
digitalWrite(trigPin, HIGH); //10 microsecond HIGH trig pulse
delayMicroseconds(10);
digitalWrite(trigPin, LOW); //end of pulse, trig pin is LOW until loop starts again
duration = pulseIn(echoPin, HIGH); //measures how long it takes pulse to go from HIGH to LOW
distance = duration / 148;
Serial.println(distance);
delay(50);
}
I may be interpreting this wrong, but when the trig pulse goes from HIGH to LOW, it stays low until the loop restarts and writes the trig pin HIGH again...so I'm just trying to figure out why the sensors needs to set the trig pin to low again, even though the trig pin is LOW when it get to the end of the loop.
I want to understand because doing it the "redundant way" seems to run smoother...but to me, it reads like this:
This is my explanation; not much experience with the HC-SR04 though, I only played with it a little.
You need to guarantee that the pin is low before setting it high, else there is no pulse. Hence the loop starts with LOW and it needs to be there for a short while. You can move the first digitalWrite to setup(), it should not make a difference.
The second 'LOW' one is there to create the actual pulse. (low to high to low).
Based in the code, be aware that there needs to be a small delay after the pin goes low, else the HC-SR04 will not see it. The delay(50) basically masks this.
Why not put a LOW write in setup(), so the loop() code just has a HIGH write followed by a LOW write?
Better still, put the ranging code in its own function.
If the trigger pin was already HIGH when you entered loop(), how would you make a 10 uS HIGH pulse when already HIGH?
The code writer couldn't know what you might put in setup(), like inadvertently writing trigger pin HIGH.
After the first iteration of loop() it don't matter no more as long as you don't write trigger pin HIGH before looping again.
edgemoron:
If the trigger pin was already HIGH when you entered loop(), how would you make a 10 uS HIGH pulse when already HIGH?
The code writer couldn't know what you might put in setup(), like inadvertently writing trigger pin HIGH.
After the first iteration of loop() it don't matter no more as long as you don't write trigger pin HIGH before looping again.
If you're worried about inadvertently writing a HIGH to a pin, you might as well go the whole defensive programming hog, and making sure that you do a pinMode before every write.