今天我们再来分享一个流水灯,也叫跑马灯哈!
一、目的
使用Wokwi仿真micropython on ESP32开发板实现跑马灯(4个LED)
二、环境
仿真网站Wokwi,语言MicroPython,开发板ESP32
三、代码解析
main.py:
- from machine import Pin
- import machine
- import time
-
- # 定义每个角,脚的状态为输出。
- pins = [machine.Pin(p, machine.Pin.OUT) for p in [32,33,25,26]]
-
- def setPins(values): # 定义每个脚的值,也就是每个灯的值
- for i in range(4):
- pins[i].value(values[i])
-
- def runLed(speed): # 定义跑马灯函数
- while True: # 写一个死循环
- setPins([1,0,0,0]) # 一次传给每个LED灯的值,值为1对应的灯亮
- time.sleep_ms(speed) # 设置跑马灯的速度
- setPins([0,1,0,0])
- time.sleep_ms(speed)
- setPins([0,0,1,0])
- time.sleep_ms(speed)
- setPins([0,0,0,1])
- time.sleep_ms(speed)
-
- runLed(200) # 运行跑马灯函数
diagram.json:
- {
- "version": 1,
- "author": "Anonymous maker",
- "editor": "wokwi",
- "parts": [
- {
- "type": "wokwi-esp32-devkit-v1",
- "id": "esp",
- "top": 0,
- "left": 0,
- "attrs": { "env": "micropython-20220618-v1.19.1" }
- },
- {
- "type": "wokwi-led",
- "id": "led1",
- "top": -65.43332926432292,
- "left": -185.83333333333334,
- "attrs": { "color": "red" }
- },
- {
- "type": "wokwi-led",
- "id": "led2",
- "top": -64.43,
- "left": -151.5,
- "attrs": { "color": "green" }
- },
- {
- "type": "wokwi-led",
- "id": "led3",
- "top": -65.44,
- "left": -117.84,
- "attrs": { "color": "blue" }
- },
- {
- "type": "wokwi-led",
- "id": "led4",
- "top": -63.76,
- "left": -80.17,
- "attrs": { "color": "yellow" }
- }
- ],
- "connections": [
- [ "esp:TX0", "$serialMonitor:RX", "", [] ],
- [ "esp:RX0", "$serialMonitor:TX", "", [] ],
- [ "led4:A", "esp:D32", "gold", [ "v0" ] ],
- [ "led3:A", "esp:D33", "blue", [ "v0" ] ],
- [ "led2:A", "esp:D25", "green", [ "v0" ] ],
- [ "led1:A", "esp:D26", "red", [ "v0" ] ],
- [ "led1:C", "esp:GND.2", "black", [ "v0" ] ],
- [ "led4:C", "esp:GND.2", "green", [ "v0" ] ],
- [ "led3:C", "esp:GND.2", "green", [ "v0" ] ],
- [ "led2:C", "esp:GND.2", "green", [ "v0" ] ]
- ]
- }
实现效果:
好了。大家也可以点击下方链接查看具体代码和实效:
Wokwi Arduino and ESP32 Simulatorhttps://wokwi.com/projects/343093459991659090
如果你想要实现8个,12个LED的闪烁效果,只需把列表加长,即可实现,快动手试试吧!欢迎评论区留言,谢谢!