Bailing out of PulseIn()

In the old forum I asked for help to bail out of pulseIn(): http://arduino.cc/forum/index.php/topic,49345.0.html The suggestion was to redefine the function and add a time out. That was with IDE 0020

I am reading IDE v 0022 and one of the fixes is:

  • Applying the timeout parameter of pulseIn() during measurement of the pulse, not just while waiting for it.

Does this fix the "problem" I was having? In other words, there is time out for 1- waiting for previous pulse to end 2- waiting for pulse to start 3- waiting for pulse to stop

Thanks.

Here's a relevant part of pulseIn()

    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++;

It looks like the timeout (maxloops) works on the first two waits but not the actual timing of the pulse.

You could add the timeout yourself, but rather than modifying the library function I'd copy the code to your own myPulseIn().


Rob

Personally I'd just use plain old digitalRead()and handle the up and down of the pulse as two seperate events and don't use the pulseIn library at all. You could have two unsigned long variables say pulseup and pulsedown with them storing the values of milli() or micros(). and handle them yourself in your sketch. Theres no bailing out of somebody else's code to worry about.

Thanks for the replies.

pluggy, I am just a beginner and like to leverage the libraries as much as I can, but thanks for the tip.

Graynomad, I did some more digging. 0022 adds the time out to the reading part of the code: https://github.com/arduino/Arduino/commit/4dad13532fbd9fcc14acd157d3fc20e295c38101#diff-0

Question to the implementors:

  • // to be 20 clock cycles long and have about 16 clocks between the edge

  • return clockCyclesToMicroseconds(width * 21 + 16);

The comment in the new code says 20 clock cycles long, but code uses 21 cycles. I remember in my implementation 20 was more accurate than 21... Is 21 more accurate than 20?

Thank you very much for the fix. Now I don't have to redefine pulseIn()

0022 adds the time out to the reading part of the code:

OK, I'm using 21, it makes sense to add it in the pulse width measure as well.


Rob