非常抱歉,下面是修正后的代码,排版更加清晰:import _thread
from machine import Pin, I2C
from ssd1306 import SSD1306_I2C
from umqtt.simple import MQTTClient
# 初始化SSD1306显示器
i2c = I2C(scl=Pin(5), sda=Pin(4))
oled = SSD1306_I2C(128, 64, i2c)
# 全局变量用于线程间通信
message_received = False
display_thread_running = True
# MQTT回调函数,当接收到消息时会自动调用
def on_message(topic, msg):
global message_received
if msg.decode() == "ting":
oled.fill(0)
oled.text("OK", 0, 0)
oled.show()
message_received = True
# 线程1:循环显示"hello, micro, python"
def display_thread():
while display_thread_running:
oled.fill(0)
oled.text("hello", 0, 0)
oled.text("micro", 0, 16)
oled.text("python", 0, 32)
oled.show()
# 线程2:连接MQTT服务器并监听消息
def mqtt_thread():
client = MQTTClient("my_client_id", "mqtt_server_ip")
client.set_callback(on_message)
client.connect()
client.subscribe("my_topic")
while not message_received:
client.check_msg()
# 收到mqtt消息后终止线程
global display_thread_running
display_thread_running = False
_thread.exit()
# 创建并启动线程
_thread.start_new_thread(display_thread, ())
_thread.start_new_thread(mqtt_thread, ())
请注意,上述代码中需要替换`mqtt_server_ip`为真实的MQTT服务器IP地址,并根据需要修改其他参数。同时,你需要提前安装`umqtt.simple`模块来支持MQTT功能。
这个示例中,线程1负责循环显示"hello, micro, python",线程2负责连接MQTT服务器,并在接收到消息后显示"OK"并终止线程1的循环。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |