Just spent the whole afternoon trying to get pulseIn to work grrrrrrrrrrr: it always returns 0 for me, even though I'm sure the pin I'm reading has been sent high for a while....
Here's what I tried to do: basically used the code in the reference, where it uses pulseIn to read pin 7. I have a push switch on that pin, pulled low thru a resistor when open, and pulled up to 5v when pushed.
First a question about how pulseIn actually works.... while it's waiting for the pulse and then timing it, or timing out, does the next line of code run? It seems it does, because when I switch on an led right after the pulsein, it goes on immediately, as if the program didn't pause while the pulsein did its thing.
That made we worry that the main loop was getting back to the pulsein on the next cycle, and restarting the clock....
So I put a 5 second delay at the bottom of the loop, to make sure that either my 2 second timeout will have completed (2000000 microseconds), or that my quick click of the button will have been read as a pulse.
But it ALWAYS returns 0, ie it always timesout.
Here's one version of the code.... I checked with my meter that the output from the switch is indeed going high
// trying to figure out how pulsein works
// going to pulse a high onto pin 7 thru a push switch
// pin 7 is pulled low thru 10k when switch open
// so a press/release is a low-high-low
int pin = 7;
unsigned long duration; //how long a press
void setup()
{
pinMode(pin, INPUT); //going to be reading it
pinMode(13, OUTPUT); //use the led as a marker
digitalWrite(13, LOW);
Serial.begin(9600); //going to output duration to monitor
}
void loop()
{
// two quick flashes on 13 to show we at top of loop
digitalWrite(13, HIGH);
delay(500);
digitalWrite(13, LOW);
delay(500);
digitalWrite(13, HIGH);
delay(500);
digitalWrite(13, LOW);
// now measure a high pulse on our pin, with a 2sec timeout
duration = pulseIn(pin, HIGH, 2000000); //2000000microsec = 2 sec
// should the program stop? or should code here get run?
//
delay(5000); //give ample time for switch press or timeout
//if no delay, worried that it runs thru the loop again
//.... and restarts the pulsein "loop"
Serial.println(duration);
// always returns a 0....
}
I'm missing something I think... anyone got an idea where I'm going wrong?