-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Description
Here's an idea about using Python exceptions to allow something like a button push or other external interrupt to interrupt normal program flow, without having to provide general interrupt handlers or having to poll.
For example, suppose you want a button push to interrupt a NeoPixel animation, and go on to the next animation. Instead of checking for the button push at various strategic places, we could just ask that a transition on a DigitalInOut cause an exception to be raised. The outer loop of the program would catch this exception and move on to the next animation. Here is strawman code:
import board
import digitalio
button = digitalio.DigitalInOut(board.D0)
button.pull = digitalio.Pull.UP
# Might need debouncing support here.
button.raise_exception_on_transition(digitalio.Transition.DOWN)
NUM_ANIMATIONS = 5
animation_number = 0
while True:
try:
while True:
# Animation can be interrupted at any time,
# not just when it finishes.
run_animation_once(animation_number)
except digitalio.TransitionException
animation_number = (animation_number + 1) % NUM_ANIMATIONSThis is clean and simple. The animation code needs to be able to deal with being interrupted at any time, but it probably has no interesting internal state that would be messed up by an exception.
Additional features could be that you can specify the exception, that it passes the DigitalInOut that caused it back so you can handle multiple buttons, that it does debouncing, etc.
Unlike an interrupt handler, the interrupt happens "in-line", because it's an exception. So you can't continue from where you left off, but often you don't want to anyway.