How to do it...

Let's perform the following steps:

  1. First, run the following lines of code in the REPL:
>>> from adafruit_circuitplayground.express import cpx
>>> def button_change(pressed):
...     print('pressed:', pressed)
... 
  1. This will define the button_change function, which will be called each time a change has occurred in the button state. Run the following code and then repeatedly press and release push button A:
>>> last = cpx.button_a
>>> while True:
...     if cpx.button_a != last:
...         button_change(cpx.button_a)
...         last = cpx.button_a
... 
pressed: True
pressed: False
pressed: True
pressed: False
pressed: True
pressed: False
  1. The code that follows combines all the code shown in this recipe to make one complete program. Add this to the main.py file; it will print a message each time push button A is pressed or released:
from adafruit_circuitplayground.express import cpx

def button_change(pressed):
    print('pressed:', pressed)

last = cpx.button_a
while True:
    if cpx.button_a != last:
        button_change(cpx.button_a)
        last = cpx.button_a