本帖最后由 yjmeishao 于 2019-1-28 16:16 编辑
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('KSLINKxxxxxx', 'yyyyyyyy', 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模组) 美国Adafruit也发布了多款基于Microchip SAMD51(120MHz Cortex-M4F/256KB SRAM/4KB ICache)的开源硬件板,可以完美支持MicroPython,有兴趣的可以自行去github上下载源码研究下。
|