# pulseIn questions

I am trying to get the serial monitor to display how long I held a button and the onboard LED to turn on for the same amount of time I held the button. But whenever I hold the button down, it just gives me a 0 in the serial monitor. It only gives me a non-zero when I press it very rapidly. I have the switch connected right with a pull-down resistor.

Here is my code:

int pin = 7;
int led = 13;
unsigned long duration;

void setup()
{
pinMode(pin, INPUT);
pinMode(led, OUTPUT);
digitalWrite(led, LOW);
Serial.begin(9600);
}

void loop()
{
duration = pulseIn(pin, HIGH);
digitalWrite(led, HIGH);
delay(duration/1000);
digitalWrite(led, LOW);
Serial.println(duration);
delay(1000);
}

Most switches are not "clean" contact. They always have a bouncing. ( a on-off quickly ). So the best way to test your code, is to build a 555 circuit in a monostable mode. <-- press and a pulse is created by the 555 at pin 3. The simply select the right combo of Resistor - Capacitor. I will do that if I need to test the pulseIn().

And

Serial.println(duration);

Serial.println(duration, DEC);

You will see a big number. Example : 1 000 000 = 1 second. The number will be in micro second ( 10 exp -6 )

The default timeout is 1 second. If you wait more then one second before pushing the button OR you hold it down for more than one second you will get a 0 return which means TIMEOUT.

Try pulseIn(pin, HIGH, 100000000UL) for a 100-second timeout.

@johnwasser

I did not know about the 1 second default value of pulseIn(). Thank and nice to know.

The pulseIn function is not really the correct way to time how long a mechanical switch is pressed. To that properly, to need to know the current state of the switch, and the previous state of the switch.

You use these two states to determine when a transition occurs. When the current state is not the same as the previous state, a transition has occurred - from pressed to released or from released to pressed. If you record when the transition occurs, you can time any length between pressed and released - from milliseconds to weeks.