from machine import Pin,PWM
import time
#流水灯
# leds=[ Pin(2,Pin.OUT),
# Pin(3,Pin.OUT),
# Pin(4,Pin.OUT)]
# while True:
# for led in leds:
# led.on()
# time.sleep(0.2)
# led.off()
#呼吸灯
# pwm = PWM(Pin(2))
# pwm.freq(10) # 1 kHz,远超人眼临界频率 50 Hz
# while True:
# # 渐亮:0 → 65535
# for duty in range(0, 65536, 512):
# pwm.duty_u16(duty)
# time.sleep_ms(8)
# # 渐暗:65535 → 0
# for duty in range(65535, -1, -512):
# pwm.duty_u16(duty)
# time.sleep_ms(8)
# import math
# # 把线性的 0-1 范围映射到感知均匀的亮度
# for i in range(256):
# linear = i / 255
# gamma_corrected = linear ** 2.2
# duty = int(gamma_corrected * 65535)
# pwm.duty_u16(duty)
# time.sleep_ms(8)
#按键控制
led=Pin(2,Pin.OUT)
btn=Pin(11,Pin.IN,Pin.PULL_UP)
while True:
if btn.value()==0:
led.on()
else:
led.off()
time.sleep_ms(20)
#中断
from machine import Pin
import time
led = Pin(2, Pin.OUT)
btn = Pin(14, Pin.IN, Pin.PULL_UP)
last_press_ms = 0
def on_button_press(pin):
global last_press_ms
now = time.ticks_ms()
# 消抖:两次触发间隔 < 200 ms 则忽略
if time.ticks_diff(now, last_press_ms) > 200:
led.toggle() # 切换 LED 状态
last_press_ms = now
# IRQ_FALLING = 检测下降沿(从高变低 = 按下瞬间)
btn.irq(trigger=Pin.IRQ_FALLING, handler=on_button_press)
# 主循环现在空闲了,可以做其他事
while True:
print("主循环运行中,等待按钮...")
time.sleep(1)