The Circuit Playground Express has two buttons. Button A is on the left and button B is on the right. These buttons can be used as inputs, which means you can use them to tell your board to do something when you press them.
In this example, we'll use the buttons of the CPX to change the colors of the NeoPixels. Button A will turn them red, and B will turn them blue.
- First
import digitalio,board, andneopixel. - Next from the NeoPixel category, drag in an
np = neopixel.NeoPixel()block and set it equal toboard.NEOPIXEL, 10, brightness = 0.2. This sets up the NeoPixels and determines brightness (can be between0.0and1.0). - Now drag in an
np = fill()block and set it to(0,0,0). This sets the NeoPixels to the color to black or off.
- In order to control the buttons, we need to create some variables to assign to button Aa and button B.
- To do this, drag in a
varblock inBasic. - In the drop down menu click Rename variable
- Next name the variable as "button_a" and hit ok.
- Now you have a variable for button_a!
- Repeat for button_b
- To set up the buttons, drag in a
DigitalInOut()block from theDigitalblock category. Choose the variable from the drop down menu asbutton_a. Set the block equal toboard.BUTTON_A. - Now drag in a
.direction =block and set it equal toDirection.INPUTchoosingbutton_afrom the drop down menu. - Then drag in a
.pull =block and set it equal toPull.DOWN. - Repeat the above steps for
button_b.
- Drag in a
while: Trueloop. - Next drag in an
ifstatement with the condition set asbutton_a.value(this block can be found inDigital) - From
Neopixeldrag innp.fill()and set it to(255,0,0)which is Red. (R,G,B) - Then drag in an
np.show()block. - Now put an
elif(meaning else if) block setting the condition tobutton_b. - Repeat steps above but set the color to
(0,0,255)for blue.
Download the file and drag to the CPX.
Try it out!
When button A is pressed, NeoPixels should turn red.
When button B is pressed they should turn blue!
Here are the code files if you want to upload directly to EduBlocks or the CPX.
np = None
button_a = None
button_b = None
from digitalio import *
import board
import neopixel
np = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness = 0.2)
np.fill((0,0,0))
np.show()
button_a = DigitalInOut(board.BUTTON_A)
button_a.direction = Direction.INPUT
button_a.pull = Pull.DOWN
button_b = DigitalInOut(board.BUTTON_B)
button_b.direction = Direction.INPUT
button_b.pull = Pull.DOWN
while True:
if button_a.value:
np.fill((255,0,0))
np.show()
elif button_b.value:
np.fill((0,0,255))
np.show()
Page last edited March 08, 2024
Text editor powered by tinymce.