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.
- The built-in NeoPixel, highlighted in red, is labeled NEO on the QT Py RP2040 board. It is located next to the reset button, inside the SCK and MI pin labels on the silk.
- The built-in button, highlighted in purple, is labeled BOOT on the board. It is located next to the A3 and SDA labels on the silk.
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.
# SPDX-FileCopyrightText: 2021 Kattni Rembor for Adafruit Industries # # SPDX-License-Identifier: MIT """CircuitPython Digital Input example - Blinking a built-in NeoPixel LED using a button switch.""" 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 Root Folder / of the CIRCUITPY drive:
- code.py
And in the lib folder on your CIRCUITPY drive:
- adafruit_pixelbuf.mpy
- neopixel.mpy
Now, press the button. The NeoPixel lights up! Let go of the button and the NeoPixel turns off.
If your NeoPixel does not 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!
Text editor powered by tinymce.