pulseIn()
returns an unsigned long
(32 bits) not an int
(16 bits), so you may have some truncation occurring in your program leading to a 0
value.
Hence you should modify your program as follows:
int pulsepin = 8;
unsigned long value = 0;
void setup()
{
pinMode(pulsepin, INPUT);
Serial.begin(9600);
}
void loop()
{
value = pulseIn(pulsepin, HIGH);
Serial.println(value);
delay(1000);
}
Also beware that pulseIn()
has a timeout (it will not wait forever).
This timeout is used for the whole completion of the pulse, i.e. first waiting for the signal to get HIGH
, then waiting for it to get back LOW
. If no pulse is detected and complete (LOW -> HIGH -> LOW) within this time, then pulseIn()
will return 0.
Default timeout value is 1 second, but you can set any value (in microseconds) you want that can hold in an unsigned long
:
e.g. if you need 10 seconds, then:
value = pulseIn(pulsepin, HIGH, 10000000UL);
I am not sure why you use delay(1000)
in your loop()
, I would remove it as a pulse may occur during that time and it would not be seen by your program.
Here is a suggested update (I also used const
where it made sense but that won't change program behavior):
const unsigned long PULSEIN_TIMEOUT = 10000000UL;
const int pulsepin = 8;
unsigned long value = 0;
void setup()
{
pinMode(pulsepin, INPUT);
Serial.begin(9600);
}
void loop()
{
value = pulseIn(pulsepin, HIGH, PULSEIN_TIMEOUT);
Serial.println(value);
}
You may also want to avoid printing 0 values since they mean no pulse was detected:
void loop()
{
value = pulseIn(pulsepin, HIGH, PULSEIN_TIMEOUT);
if (value > 0)
Serial.println(value);
}