[Digi-Key Follow Me Issue 2] Task 3: Control WS2812B
[Copy link]
Task 3: Use buttons to control the display and color switching of the onboard Neopixel LED
My control idea here is very simple, that is, a short press of the button can switch 7 colors, a long press can directly turn off the colored lights, and a super long press can display the rainbow gradient effect. The touch pin of the esp32s3 board is also used here. The touch pin can use the capacitive touch pin as a button. After a super long press, the pin below the touch board can turn on the rainbow gradient, and touching the pin above will exit.
The effects are as follows: duanan is a short press, changan is a long press, and chaochangan is an ultra-long press.
任务3
code show as below:
import time, board, neopixel, digitalio
from rainbowio import colorwheel
import touchio
color = [(255,0,0), (0,255,0), (0,0,255), (0,255,255),\
(255,0,255), (255,255,0), (255,255,255), (0,0,0)]
pixel = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=1) #brightness为亮度0到1的小数
button = digitalio.DigitalInOut(board.BUTTON)
button.direction = digitalio.Direction.INPUT
button.pull = digitalio.Pull.UP
touch_one = touchio.TouchIn(board.D12)
touch_two = touchio.TouchIn(board.A4)
state = 0
press_time = 0
def rainbow(delay):
while not touch_one.value: #是否触摸
pass
if touch_one.value:
while True:
for color_value in range(255):
pixel.fill(colorwheel(color_value))
if touch_two.value:
break
time.sleep(delay)
if touch_two.value:
break
pixel.fill((0,0,0))
while True:
if state >= len(color):
state = 0
time.sleep(0.01) #延时消抖
if button.value == 0: #按键按下
while not button.value: #判断按键是否起来,区别长按短按
press_time += 0.001
if 0 <= press_time <= 200: #3秒左右
print(press_time, 'duanan')
pixel.fill(color[state])
state += 1
elif 200 < press_time <= 500:
print(press_time, 'changan') #5s以上
pixel.fill((0,0,0))
state = 0
else:
print('changchaoan')
print('touch above begin rainbow show, and touch below exit')
rainbow(0.002)
state = 0
press_time = 0
It was relatively easy to complete, mainly because the neopixel library is very convenient for controlling RGB colored lights, and the official also has related routines. At first, I didn't know how to use pin pins, and I didn't know how to use button GPIO input and output, because it was a little different from the MicroPython function, but I learned it after all.
|