The CircuitPython digitalio module has many applications. The basic Blink program sets up the LED as a digital output. You can just as easily set up a digital input such as a button to control the LED. This example builds on the basic Blink example, but now includes setup for a button switch. Instead of using the time module to blink the LED, it uses the status of the button switch to control whether the LED is turned on or off.

LED and Button

Built-in LED:

  • The built-in red LED (indicated by the magenta box in the image), labeled 13 on the silk, is located above the USB connector.

Button wiring:

  • One leg of button to Feather GND
  • Opposite leg of button to Feather A1

If you're unsure of which legs on a button are "opposite", you can guarantee you're using the proper legs if you connect the wires up to two legs located diagonally across the button, like in the diagram.

Controlling the LED with a Button

Save the following as code.py on your CIRCUITPY drive.

# SPDX-FileCopyrightText: 2021 Kattni Rembor for Adafruit Industries
#
# SPDX-License-Identifier: MIT
#
"""CircuitPython Digital Input example for Feather RP2040"""
import board
import digitalio

led = digitalio.DigitalInOut(board.LED)
led.direction = digitalio.Direction.OUTPUT

button = digitalio.DigitalInOut(board.A1)
button.switch_to_input(pull=digitalio.Pull.UP)

while True:
    if not button.value:
        led.value = True
    else:
        led.value = False

Now, press the button. The LED lights up! Let go of the button and the LED turns off.

Even though the wires are both above the button, the wiring is the same as the wiring diagram above!

Note that the code is a little less "Pythonic" than it could be. It could also be written as led.value = not button.value. That way is more difficult to understand if you're new to programming, so the example is a bit longer than it needed to be to make it easier to read.

First you import two modules: board and digitalio. This makes these modules available for use in your code. Both are built-in to CircuitPython, so you don't need to download anything to get started.

Next, you set up the LED. To interact with hardware in CircuitPython, your code must let the board know where to look for the hardware and what to do with it. So, you create a digitalio.DigitalInOut() object, provide it the LED pin using the board module, and save it to the variable led. Then, you tell the pin to act as an OUTPUT.

You include setup for the button as well. It is similar to the LED setup, except the button is an INPUT, and requires a pull up.

Inside the loop, you check to see if the button is pressed, and if so, turn on the LED. Otherwise the LED is off.

That's all there is to controlling an LED with a button switch!

This guide was first published on Mar 05, 2021. It was last updated on 2021-06-08 12:05:37 -0400.

This page (Digital Input) was last updated on Nov 30, 2021.

Text editor powered by tinymce.