Buttons and Switch

We're going to use CircuitPython, Mu, and the two buttons and one switch on Circuit Playground Express to plot button presses and the switch location. We'll run this code on our Circuit Playground Express and use Mu to plot the data that CircuitPython prints out.

Save the following as code.py on your Circuit Playground Express board, using the Mu editor:

import time

import board
import digitalio

button_a = digitalio.DigitalInOut(board.BUTTON_A)
button_a.direction = digitalio.Direction.INPUT
button_a.pull = digitalio.Pull.DOWN

button_b = digitalio.DigitalInOut(board.BUTTON_B)
button_b.direction = digitalio.Direction.INPUT
button_b.pull = digitalio.Pull.DOWN

switch = digitalio.DigitalInOut(board.SLIDE_SWITCH)
switch.direction = digitalio.Direction.INPUT
switch.pull = digitalio.Pull.UP

while True:
    if button_a.value:
        print((1,))
    elif button_b.value:
        print((2,))
    elif switch.value:
        print((-1,))
    else:
        print((0,))
    time.sleep(0.1)

Our code is very simple. First we import digitalio, board and time. Then, we create the button_a, button_b and switch objects.

Our main loop consists of if, elif, and else statements. An elif statement says "otherwise, if" something happens, do a thing. An else statement says "otherwise do" a thing regardless of what is happening. So, our main loop reads: if button A is pressed, print 1, otherwise, if button B is pressed, print 2, otherwise, if the switch is moved to the right, print -1, otherwise print 0. Therefore, it will print 0 until you press a button or move the switch. Then we have a time.sleep(0.1) to keep from spamming the results - if they move too quickly they're difficult to read!

Note that the Mu plotter looks for tuple values to print. Tuples in Python come in parentheses () with comma separators. If you have two values, a tuple would look like (1.0, 3.14) Since we have only one value, we need to have it print out like (1.0,) note the parentheses around the number, and the comma after the number. Thus the extra parentheses and comma in print((1,)), print((2,)), etc.

Once you have everything setup and running, try pressing one of the buttons on the Circuit Playground Express, and watch the plotter immediately react! When you press button A or button B, the plotter line goes up. If you move the switch to the right, the plotter line goes up!

This is a great way to test the buttons and switch on the Circuit Playground Express and plot different numbers simply by printing them!

This guide was first published on Apr 09, 2018. It was last updated on Apr 09, 2018. This page (Buttons and Switch) was last updated on Dec 12, 2018.