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?

3 Answers 3


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.


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).


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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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