Here's the code from wiring_pulse.c
/* Measures the length (in microseconds) of a pulse on the pin; state is HIGH
* or LOW, the type of pulse to measure. Works on pulses from 2-3 microseconds
* to 3 minutes in length, but must be called at least a few dozen microseconds
* before the start of the pulse. */
unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout)
{
// cache the port and bit of the pin in order to speed up the
// pulse width measuring loop and achieve finer resolution. calling
// digitalRead() instead yields much coarser resolution.
uint8_t bit = digitalPinToBitMask(pin);
uint8_t port = digitalPinToPort(pin);
uint8_t stateMask = (state ? bit : 0);
unsigned long width = 0; // keep initialization out of time critical area
// convert the timeout from microseconds to a number of times through
// the initial loop; it takes 16 clock cycles per iteration.
unsigned long numloops = 0;
unsigned long maxloops = microsecondsToClockCycles(timeout) / 16;
// wait for any previous pulse to end
while ((*portInputRegister(port) & bit) == stateMask)
if (numloops++ == maxloops)
return 0;
// wait for the pulse to start
while ((*portInputRegister(port) & bit) != stateMask)
if (numloops++ == maxloops)
return 0;
// wait for the pulse to stop
while ((*portInputRegister(port) & bit) == stateMask)
width++;
// convert the reading to microseconds. The loop has been determined
// to be 10 clock cycles long and have about 16 clocks between the edge
// and the start of the loop. There will be some error introduced by
// the interrupt handlers.
return clockCyclesToMicroseconds(width * 10 + 16);
}
I took a look at this, and then realized that I probably hadn't read the doc carefully enough, because it will return 0 if a pulse does not start before the timeout, but will not return 0 if the pulse does not end before the timeout. Sure enough, from:
http://www.arduino.cc/en/Reference/PulseIn
"Gives up and returns 0 if no pulse starts within a specified time out."
So that's all cleared up.
Now, adding the ability to return 0 if the pulse does not end before the timeout is easy enough:
// wait for the pulse to stop
while ((*portInputRegister(port) & bit) == stateMask)
if (numloops++ == maxloops)
return 0;
width++;
but how do I adjust the width-to-microseconds conversion so that it will be accurate with the new while loop time? I understand you can look at the assembly code and then look up how many clock cycles each command takes, but I've never done it and I need some hand holding, if you don't mind.
thanks,
Max