The GPIO pins on the MinnowBoard MAX can be configured to receive data, such as a button press. Additionally, we can use these inputs to trigger an interrupt in a program, activating an Interrupt Service Routine (ISR).
In [ ]:
# Import mraa and time for GPIO access and use of the sleep function
import mraa
import time
Using Python interrupts is a bit complicated since the Interrupt Servie Routine (ISR) module for Python can only work with objects. Basic types won't work, so you'll need to declare a class to use the objects. In this case, we use a class to keep track of the status of one of the LEDs. When the button is pressed, we'll flip the LED.
In [ ]:
# Calling an interrupt requires that we specify a function to run when the
# interrupt is triggered. This class simply holds our GPIO that flips upon
# interrupt. The LED is held in the led object, and the current state
# of the LED is held in status
class Counter:
status = False
led = mraa.Gpio(25)
led.dir(mraa.DIR_OUT)
# Create an instance of the class
c = Counter()
# This is the function that will be called when the interrupt happens. It will
# flip the status as it is held by the class and apply it to the GPIO pin.
def test(args):
c.status = not c.status
c.led.write(c.status)
Here is were we'll use the interrupt. After declaring the interrupt specifying the function to use, we'll specify another LED to blink endlessly wherein we can interrupt that procedure.
In [ ]:
# Initialize the pin to be used as input
x =mraa.Gpio(26)
x.dir(mraa.DIR_IN)
# This tells the pin to watch for interrupts. mraa.EDGE_BOTH is what we're watching
# for; we can specify looking for the pin to go HIGH or LOW, but here we don't care
# as long as it changes. The second argument is the function to call, and the third can
# hold arguments that can be passed into the function (you can pass more than one)
x.isr(mraa.EDGE_BOTH, test, test)
# When the default pin, is specified, it runs a normally blinking pattern
y = mraa.Gpio(23)
y.dir(mraa.DIR_OUT)
Here is where we enter an infinite loop, but we can issue an interrupt to change the other LED. Despite being in a while loop that doesn't deal with the GPIO on pin 25, we can use an ISR to change it wherever we are.
In [ ]:
# This runs the rest of the program, but it can be interrupted
# as you can see by triggering the interrupt pin
while True:
y.write(1)
time.sleep(1)
y.write(0)
time.sleep(1)