Pulsein

In general I have had great luck with Arduino and enjoyed it very much. I am having difficulty with plusein however. It will not give a consistent result in the following sketch. I have tried both high and low transitions and have pulled the input pin to ground through a 10K resistor. I have also tried pulses from 3 usec to 100ms. In each case the output is generally about 50% correct with the balance all over the map. Thanks in advance.

long duration;
int Signal = 7;
void setup()
{
pinMode(Signal, INPUT);
Serial.begin(9600);
}

void loop()
{
duration = pulseIn(Signal, HIGH);
Serial.println(duration);
delay(1000);
}

It seems that the consistency of value is inversely proportional to the duty cycle of the pulse measured. My comments earlier were at 50% duty cycle. At 10-20% duty cycle the pulse is correctly measured about 80% of the time.

I think the problem has something to do with the fact that if you call pulseIn() in the middle of a pulse (i.e. when the signal is already HIGH), it will return the length of the remainder of the pulse. It doesn't wait for the signal to go LOW and then HIGH again. You could try doing two pulseIn()'s in a row (both HIGH) and just using the result of the second one.

I'm not sure what the expected behavior is for a function like this: when measuring a HIGH pulse, should it wait for a rising edge to start counting the length of a pulse, or should it begin counting immediately if the signal is already HIGH?

Very good. Executing pulsein twice and taking the second value works perfectly. I measure consistent results from 10usec to 800ms with no problem. In my opinion the function should wait for the transition and then make the measurement for the duration of that high or low period depending on what you asked for. As if starting a stopwatch on the transition and stopping it on the next transition. Thanks.