LED(发光二极管)是一种半导体发光器件,电流正向流过时发光。
[接线图占位,后续添加]
文字说明(具体接法见下方代码注释):
GNDPin(25);Pico W / Pico 2 W 的板载 LED 挂在无线芯片上,要用 Pin("LED")GND# ============ 接线 ============
# LED 长脚(正极) → 220Ω~1kΩ 电阻 → Pico GP15
# LED 短脚(负极) → Pico GND
# 电阻一定要串,否则电流过大烧 LED 和 GPIO
# =============================
from machine import Pin
import time
led = Pin(15, Pin.OUT) # 外接 LED 接在 GP15
print('LED 闪烁')
while True:
led.on() # 点亮
time.sleep(0.5)
led.off() # 熄灭
time.sleep(0.5)
# ============ 接线 ============
# 板载 LED 不用接线,芯片内部已连好
# 注意:Pico(非 W 版) 板载 LED 在 Pin(25)
# Pico W / Pico 2 W 板载 LED 挂在无线芯片上,必须用 Pin("LED") 才点得亮
# =============================
from machine import Pin
import time
# 普通 Pico 用 Pin(25);Pico W / Pico 2 W 改成 Pin("LED")
led = Pin(25, Pin.OUT)
while True:
led.toggle() # 翻转亮/灭,比 on/off 更省事
time.sleep(0.5)
# ============ 接线 ============
# 同"外接 LED 闪烁":LED 长脚 → 电阻(220Ω~1kΩ) → GP15,短脚 → GND
# =============================
from machine import Pin, PWM
import time
pwm = PWM(Pin(15))
pwm.freq(1000) # 1kHz,频率够高肉眼就看不到闪烁
print('LED 亮度调节')
while True:
# 由暗到亮
for duty in range(0, 65536, 1000):
pwm.duty_u16(duty)
time.sleep_ms(20)
# 由亮到暗
for duty in range(65535, -1, -1000):
pwm.duty_u16(duty)
time.sleep_ms(20)
# ============ 接线 ============
# 共阴 RGB LED(4 脚,最长那脚是公共负极 → GND)
# R 脚 → 电阻(220Ω) → GP15
# G 脚 → 电阻(220Ω) → GP14
# B 脚 → 电阻(220Ω) → GP13
# 公共脚(最长、带缺口侧的中间脚) → GND
# =============================
from machine import Pin, PWM
import time
red = PWM(Pin(15))
green = PWM(Pin(14))
blue = PWM(Pin(13))
red.freq(1000); green.freq(1000); blue.freq(1000)
def set_color(r, g, b):
"""设置 RGB 颜色,r/g/b 取值 0~255"""
# duty_u16 需要 0~65535,把 0~255 映射到 0~65535
red.duty_u16(int(r * 65535 / 255))
green.duty_u16(int(g * 65535 / 255))
blue.duty_u16(int(b * 65535 / 255))
colors = [
(255, 0, 0), # 红
(0, 255, 0), # 绿
(0, 0, 255), # 蓝
(255, 255, 0), # 黄
(255, 0, 255), # 紫
(0, 255, 255), # 青
(255, 255, 255) # 白
]
print('RGB LED 颜色变化')
while True:
for c in colors:
set_color(*c)
print('颜色:', c)
time.sleep(1)
Pin(25);Pico W / Pico 2 W 必须用 Pin("LED"),用 Pin(25) 点不亮。duty_u16 范围是 0~65535,不是 0~255,颜色映射要乘 65535/255。Q: 外接 LED 不亮怎么办? A: 查极性(长脚经电阻接 GPIO、短脚接 GND)、电阻有没有接、GPIO 脚号对不对。
Q: 板载 LED 在 Pico W 上点不亮?
A: Pico W / Pico 2 W 的板载 LED 不在 GPIO25,改用 Pin("LED")。
Q: RGB 颜色不对或太暗?
A: 确认是共阴还是共阳;确认 duty_u16 用的是 0~65535(不是 0~255)。