I need to catch a fast GPIO pulse in a while loop like so

while True:
    if GPIO.input(11) == 1:

the pulse is so fast (magnet passing by a switch), that if I add a sleep in the while, of just even .5, it will miss the value in some cases.. without one, even with an internal pulldown, it will get a random false 1 pretty much instantly.. Is there some way to remove the sleep, and have it reliable? Is this something ony an external pulldown would solve?


Polling for input, in any language, is a poor solution.

Python makes it simple to catch interrupts e.g.

    # set an interrupt on a falling edge and wait for it to happen
    GPIO.wait_for_edge(INT, GPIO.FALLING)

NOTE this blocks the process, until an interrupt occurs, so it is best to do it on a background process.

| improve this answer | |

Any GPIO library you choose to use will almost certainly provide an interrupt capability.

Use that interrupt capability to inform you when the GPIO level changes from 0 to 1 (rising edge), or from 1 to 0 (falling edge) or on either change.

By the way I've used Hall effect sensors to detect magnets spinning on a shaft at about 9000 RPM (from memory).

| improve this answer | |

Depending on the application you may want to consider a hardware solution. You can detect a very brief pulse and use that to trigger a monostable that communicates with the Pi. External hardware can do signal-conditioning and cope with things like contact-bounce in switches. How clean is your input signal?

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.