开启MicroPython多线程模式

时间:2024-05-23 18:01:52

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():
        semp.pend()
        print('sem_thread run')

def i2c_thread():
        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_):
        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_):
        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模组)开启MicroPython多线程模式