The CircuitPython digitalio module has many applications. You can easily set up a digital input such as a button to control the NeoPixel 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.

NeoPixel and Button

  • Towards the top left of the main part of the board is the NeoPixel LED (highlighted in green).
  • Towards the bottom right of the main part of the board is the BOOT button (highlighted in red).

Controlling the NeoPixel with a Button

To use the built-in NeoPixel on your board, you need to first install the NeoPixel library into the lib folder on your CIRCUITPY drive.

Then you need to update code.py.

Click the Download Project Bundle button below to download the necessary libraries and the code.py file in a zip file. Extract the contents of the zip file, and copy the entire lib folder and the code.py file to your CIRCUITPY drive.

"""CircuitPython Digital Input Example for QT2040 Trinkey"""
import board
import digitalio
import neopixel

pixel = neopixel.NeoPixel(board.NEOPIXEL, 1)

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

while True:
    if not button.value:
        pixel.fill((255, 0, 0))
    else:
        pixel.fill((0, 0, 0))

Your CIRCUITPY drive contents should resemble the image below.

You should have in / of the CIRCUITPY drive:

  • code.py

And in the lib folder on your CIRCUITPY drive:

  • adafruit_pixelbuf.mpy
  • neopixel.mpy
CIRCUITPY

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

If your NeoPixel does light up when you press the button, make sure you've copied all the necessary files and folders to the CIRCUITPY drive!

First you import two modules, board and digitalio, and one library, neopixel. This makes these modules available for use in your code.

Next, you set up the NeoPixel. 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 neopixel.NeoPixel() object, provide it the NeoPixel LED pin using the board module, and tell it the number of NeoPixels, 1. You save this object to the variable pixel.

Then, you create a digitalio.DigitalInOut() object, provide it the button pin using the board module, and save it to the variable button. You tell the pin to act as an INPUT, and provide a pull up.

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

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

This guide was first published on Jun 23, 2021. It was last updated on 2021-06-24 13:02:45 -0400.

This page (Digital Input) was last updated on Sep 18, 2021.

Text editor powered by tinymce.