[esp32]ESP8266使用micropython连接MQTT控制家电

By Heanny
2022-04-05
2215 read

设备

  • ESP8266继电器
  • ESP8266固件烧录器
  • ESP-01S
    如图

软件

  • Thonny
  • AiThinker_Serial_Tool_V1.2.3
  • flash_download_tools_v3.6.8
  • esp8266-20190529-v1.11.bin

概要

经历了很长很长很长很长的时间,跳过了各种坑,终于,在居家隔离的日子里,把这个项目搞定了
首先呢,淘宝购买了设备,先用 Raspberry pi RP 连接ESP01S、控制继电器,联网,控制电器,发现硬件多、预算高,然后就更换成了ESP8266继电器。刷了很长很长时间的固件,发现只能成功刷入原厂AT,micropython刷不进去,或者刷进去启动乱码,毕竟咱们AT语句不熟,最后,搁置了一段时间,成功刷入micropython

  1. 刷固件
    下载软件flash_download_tools_v3.6.8,好像百度一大堆,大同小异,然后选择固件esp8266-20190529-v1.11.bin,输入开始位置0x00000,清除ERASE,然后开始刷入START,

    刷入成功之后,使用AiThinker_Serial_Tool_V1.2.3连接,你会看到一堆乱码,然后是熟悉的python命令行

    然后编写boot.py文件,
import network import time from machine import Pin from umqtt.simple import MQTTClient import usocket as socket status = 'run' server = "192.168.0.10" port = 1883 ClientId = "0" TOPIC = b"iot_eps32_001" username = 'iot' password = 'passwd' # 继电器 g0 = Pin(0, Pin.OUT, value=0) # 指示灯 g2 = Pin(2, Pin.OUT, value=0) client = None print("clientid:", ClientId, "\n", "Broker:", server, "\n", "User Name:", username, "\n", "Password:", password, "\n") def do_connect(): sta_if = network.WLAN(network.STA_IF) ap_if = network.WLAN(network.AP_IF) if ap_if.active(): ap_if.active(False) if not sta_if.isconnected(): print('connecting to network...') sta_if.active(True) sta_if.connect('wifissid', 'wifipasswd') # wifi的SSID和密码 while not sta_if.isconnected(): pass print('network config:', sta_if.ifconfig()) return def sub_cb(topic, msg): global client, status topic = topic.decode('utf-8') msg = msg.decode('utf-8') print(topic, ':', msg) if topic == 'iot_eps32_001': if msg == 'close': status = 'close' # client.disconnect() return elif msg == 'test': g2.on() time.sleep(1) g2.off() time.sleep(2) g2.on() time.sleep(1) g2.off() time.sleep(2) g2.on() elif msg == 'on': g0.on() elif msg == 'off': g0.off() pass return def connect(): global client client = MQTTClient(client_id=ClientId, server=server, port=port, user=username, password=password, keepalive=60) # please make sure keepalive value is not 0 client.set_callback(sub_cb) client.connect() print(client, status) client.subscribe(TOPIC) print("Connected to %s, subscribed to %s topic" % (server, TOPIC)) while status == 'run': client.wait_msg() time.sleep(0.01) pass client.disconnect() return if __name__ == '__main__': do_connect() connect()

修改你的mqtt服务器账户密码,WIFI账户密码,就可以使用了

推送消息到手机
[esp32]esp8266连接小爱同学控制继电器

Comments

暂无评论,还不快来坐沙发...

Leave a Reply