Skip to content

ESP32 控制 LED 闪烁

接线示意

用 ESP32 的 GPIO4 驱动一颗 LED,每隔 0.5 秒 亮灭一次。可先在 Wokwi 在线仿真,再上真机。

在线仿真

  1. 打开 https://wokwi.com/
  2. My projectsNew project → 选择 ESP32MicroPython
  3. 将下方 main.pydiagram.json 分别粘贴到对应文件
  4. 点击 Start 运行,观察 LED 闪烁

main.py

python
from machine import Pin
import time

led = Pin(4, Pin.OUT)  # GPIO4,对应接线 D4

while True:
    led.on()           # HIGH,亮
    time.sleep(0.5)
    led.off()          # LOW,灭
    time.sleep(0.5)

diagram.json

json
{
  "version": 1,
  "author": "",
  "editor": "wokwi",
  "parts": [
    { "type": "board-esp32-devkit-c-v4", "id": "esp", "top": 0, "left": 0, "attrs": {} },
    { "type": "wokwi-led", "id": "led1", "top": -42, "left": 167, "attrs": { "color": "red" } },
    {
      "type": "wokwi-resistor",
      "id": "r1",
      "top": 70.6,
      "left": 162.35,
      "rotate": 270,
      "attrs": { "value": "220" }
    }
  ],
  "connections": [
    [ "esp:GND.2", "led1:C", "green", [ "v0" ] ],
    [ "esp:4", "r1:1", "green", [ "h0" ] ],
    [ "r1:2", "led1:A", "green", [ "h0" ] ]
  ],
  "dependencies": {}
}

接线说明

ESP32元件
GPIO4220Ω 电阻 → LED 正极(阳极)
GNDLED 负极(阴极)

电阻与 LED 串联,限流约 220Ω,避免电流过大烧毁 LED。