Reading the buttons

The board has two press buttons. The following code reads the state of each button (False if the button is not pressed and True if the button is pressed).

import time
import board
import digitalio
import neopixel

buttonA = digitalio.DigitalInOut(board.BUTTON_A)
buttonA.switch_to_input(pull=digitalio.Pull.DOWN)

buttonB = digitalio.DigitalInOut(board.BUTTON_B)
buttonB.switch_to_input(pull=digitalio.Pull.DOWN)

leds = neopixel.NeoPixel(board.NEOPIXEL, 10)

while True:
    a_pressed = buttonA.value
    b_pressed = buttonB.value
    print(a_pressed, b_pressed)
    time.sleep(0.25)

You should see output like this (no buttons pressed). As soon as you press a button, the output should change.

Untitled

Challenges

Challenge 1

Edit the code above to get the following behavior. When pressing (and holding) button A, one of the LEDs turns on. When pressing (and holding) button B, another LED comes on. If no buttons are pressed, all LEDs are off.

Challenge 2

Start from the code below (click on the ▶️ symbol to see the code) to write a program that makes the board say ‘hello’ when button A is pressed and ‘goodbye’ when button B is pressed.

To make the example code below work, you will have to add the two following sound files to the board. Download the files to the computer and then copy them to the board. Here is a screenshot of what the files on the board would look like.

Untitled

hello.wav

goodbye.wav

Once you have uploaded the files, the functions hello() and goodbye() play the respective sounds.

Challenge 3

If no buttons are pressed, all LEDs are off. If you hold button A, LEDs start coming on. For each additional 500 ms holding button A, another LED comes on. After holding button A for 25 seconds (25 x 500 ms), all the LEDs are on for 1 second. Then, they are all switched off, and the cycle recommences. If button A is released, all LEDs are switched off.