You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Raspberry Pi Pico的Python无需等待函数执行完毕即可启动新函数?

在Raspberry Pi Pico上实现多函数并行运行

核心说明

树莓派Pico搭载的MicroPython自带_thread模块(并非标准Python的threading),无需额外安装,直接导入即可使用多线程功能。

修改后的完整代码

from machine import Pin, PWM
import time
import _thread

def dimming(PinNumber):
    PinN = PWM(Pin(PinNumber))
    PinN.freq(1000)
    for duty in range(65025):
        PinN.duty_u16(duty)
        time.sleep(0.0001)
    for duty in range(65025, 0, -1):
        PinN.duty_u16(duty)
        time.sleep(0.0001)

while True:  
    for i in range(6):
        # 启动新线程执行调光任务,参数需以元组形式传递(单参数也要加逗号)
        _thread.start_new_thread(dimming, (i,))
        time.sleep(0.3)
    # 可选:添加等待时间避免短时间内重复启动大量线程
    time.sleep(2)

关键注意事项

  • _thread.start_new_thread是MicroPython启动线程的核心方法,第一个参数为要执行的函数名,第二个参数是函数所需的参数元组。
  • 由于每个线程操作独立的PWM引脚,不存在资源竞争问题;如果后续涉及共享变量/硬件资源,需使用_thread.allocate_lock()加锁保护。
  • 主程序必须保持运行状态,一旦主循环终止,所有后台线程会随之停止。

内容的提问来源于stack exchange,提问作者luuf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 00:23:24