In the above code, if I understand the pulseIn function correctly, I'm expecting to see the LED on for a second and off for a second. But it flashes much faster (on for ~250 ms and off for ~250 ms).
With F_CPU = 16000000L, the expression becomes (a * 16000L) / 1000L. The multiplication will overflow if 'a' (the timeout value you are passing) exceeds 268435. So a timeout of one million is too much for it. [The multiplication is done using unsigned arithmetic, because that's the type of the 'timeout' parameger to pulseIn.]
LolluPaandi:
In the above code, if I understand the pulseIn function correctly, I'm expecting to see the LED on for a second and off for a second. But it flashes much faster (on for ~250 ms and off for ~250 ms).
Any thoughts? Thanks!
dc42 is probably right. Also when a parameter like "timeout" is specified in microseconds, you should be wary of supplying a million of them. The implication is that you are expecting a pulse within a "few" microseconds, and if you don't get it you timeout.
Also, a "counted" loop (like pulseIn does) is unlikely to be accurate at such high intervals (interrupts would throw the interval out).
I see your point Nick. Which is why my LED flashes approximately every one second, and not accurately. But my application can tolerate this - I'm trying to detect a light pattern from an external device (flashing 'fast' or flashing 'slow' or steady) where 'fast' is every second and 'slow' is every 3 seconds.
Also, in the documentation of pulseIn, it is mentioned that the default value of timeout is one second. But I don't see how this is implemented. Is that a bug as well?
I'm fairly new to Arduino. Is there a place to log bugs?
LolluPaandi:
Also, in the documentation of pulseIn, it is mentioned that the default value of timeout is one second. But I don't see how this is implemented. Is that a bug as well?
Yes, I think it is. This illustrates well the perils of untested, unverified code.
LolluPaandi:
Also, in the documentation of pulseIn, it is mentioned that the default value of timeout is one second. But I don't see how this is implemented. Is that a bug as well?
It's implemented in the function prototype for pulseIn in the file WProgram.h:
unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout = 1000000L);
It's pretty standard in C++ to put defaults on (trailing) arguments to functions in this fashion.
A better fix was suggested that only requires a change to the pulsein function and won't affect other code that uses microsecondsToClockCycles and wiring.h