开启MicroPython多线程模式

本文介绍在MicroPython中实现多线程的初步尝试,包括线程锁和信号量的使用,通过四个示例线程展示其运行效果,涉及LED控制、I2C读取、MQTT消息发布和接收。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

MicroPython官方版本对多线程的支持

MicroPython官方版本尝试对 多线程 的支持,但是目前的支持只停留在非常初级的阶段,离真正可用还是有一段距离。在尝试增加多线程的支持过程中踩坑无数,不过最后总算成功实现所需要的功能。

修改后的MicroPython多线程示例

多线程的基础上增加了线程锁和信号量的支持:

from umachine import Pin
import utime
import _thread

lock = _thread.allocate_lock()
semp = _thread.allocate_semephare()

定义4个用户线程,分别是信号量演示线程/i2c演示线程/LED演示线程和MQTT消息发布线程:

def sem_thread():
	while True:
        semp.pend()
        print('sem_thread run')

def i2c_thread():
	while True:
        print('i2c_thread read 0x57')
        i2c0.readfrom_mem(0x57, 0, 4)
        utime.sleep(10)
        print('i2c_thread read 0x5f')
        i2c0.readfrom_mem(0x5f, 0x9a, 6)
        utime.sleep(10)
        #_thread.exit()

def led_thread(time_):
	while True:
        print('led_thread on')
        led0.value(1)
        utime.sleep(time_)
        print('led_thread off')
        led0.value(0)
        utime.sleep(time_)
        semp.post()

def mqtt_thread(time_):
	while True:
        lock.acquire()
        print('mqtt_thread message 1')
        mqtt.publish('/home/bedroom/lamp', 'led on')
        mqtt.publish('/home/bedroom/speaker', 'music off')
        utime.sleep(time_)
        print('mqtt_thread message 2')
        mqtt.publish('/home/bedroom/lamp', 'led off')
        mqtt.publish('/home/bedroom/speaker', 'play music')
        utime.sleep(1)
        print('mqtt_thread message 3')
        mqtt.publish('/smart_home/bedroom/window', 'close window')
        utime.sleep(time_)
        lock.release()
        #_thread.exit()

MQTT消息订阅回调函数和连接成功回调函数:

def callback_on_connect(userdata, flags, rc):
        mqtt.subscribe('/home/bedroom/msgbox', 0)

def callback_on_message(userdata, message):
        print(message)
        mqtt.publish('/home/bedroom/air', 'air turn on')

Wi-Fi连接到AP的Python代码(自己写的ATWINC1500 MicroPython库):

from winc1500 import WLAN
wlan = WLAN(STA_IF)
wlan.connect('KSLINxxxxxx', 'xxxxxxxxx', AUTH_WPA_PSK)

MQTT的连接和订阅(参考前面回调函数):

from winc1500 import MQTT
mqtt = MQTT(MQTT_CLIENT)
mqtt.username_pw_set('winc_mp_mqtt', '')
mqtt.on_connect(callback_on_connect)
mqtt.on_message(callback_on_message)
mqtt.connect('iot.eclipse.org', 1883, 30)

最后是开始启动线程的操作

_thread.start_new_thread(led_thread, (2,))
_thread.start_new_thread(i2c_thread, ())
_thread.start_new_thread(sem_thread, ())
_thread.start_new_thread(mqtt_thread,(3,))

while True:
        pass

代码运行效果

补充:MicroPython代码运行在Microchip SAMV71-XULT+ATWINC1500(Wi-Fi模组)4个用户线程运行效果

评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值