12038| 7
|
[uPyCraft IDE] uPyCraft-micropython教程(dfrobot MQTT实现单向远程控制) |
MQTT简介 原料: 硬件平台:FireBeetle-ESP32 x2 软件平台:uPyCraft 0.21 物联网平台:https://iot.dfrobot.com.cn(这是dfrobot的建议物联网,后面我们会在上面增加更多有趣功能) 假定一个ESP32是设备A,另一个ESP32是设备B, 我们要实现的功能 B定时向A发送开灯关灯命令,间隔三秒 开始干活 第一步:注册物联网网站账号,https://iot.dfrobot.com.cn 这里需要填入邮箱地址,后期使用邮箱地址登录,注册很简单,这里就不上图了。 第二步:创建设备,记录user password clientid topic,要替换到程序中去 第三步:在lib目录下创建umqtt目录,再将uPy_lib/umqtt目录下的simple.py拖动到lib/umqtt目录下,完成库的烧录(设备A和设备B都要做此操作) 新建目录 输入新建的目录名称umqtt 创建成功 第四部:下载并运行代码 设备A执行下面程序(注意替换SSID PASSWORD【路由器相关】,username【网站账户】,password【网站密码】,CLIENT_ID【刚记录的clientID后面加个2】,TOPIC【刚记录的TOPIC】) [mw_shl_code=python,true]from umqtt.simple import MQTTClient from machine import Pin,Timer import network import time SSID="DFROBOT_AP" PASSWORD="12345678" led=Pin(2, Pin.OUT, value=0) SERVER = "182.254.130.180" CLIENT_ID = "S1grx_VmNW2" TOPIC_LEDA = b"B1rl_47NZ" username='H1UGxqD4-' password='BkeLGeqvVb' state = 0 def sub_cb(topic, msg): global state print((topic, msg)) if msg == b"on": led.value(0) state = 0 print("1") elif msg == b"off": led.value(1) state = 1 print("0") elif msg == b"toggle": # LED is inversed, so setting it to current state # value will make it toggle led.value(state) state = 1 - state def connectWifi(ssid,passwd): global wlan wlan=network.WLAN(network.STA_IF) wlan.active(True) wlan.disconnect() wlan.connect(ssid,passwd) while(wlan.ifconfig()[0]=='0.0.0.0'): time.sleep(1) connectWifi(SSID,PASSWORD) server=SERVER c = MQTTClient(CLIENT_ID, server,0,username,password) c.set_callback(sub_cb) c.connect() c.subscribe(TOPIC_LEDA) print("Connected to %s, subscribed to %s topic" % (server, TOPIC_LEDA)) try: while 1: c.wait_msg() finally: c.disconnect() [/mw_shl_code] 设备B执行下面程序(注意替换SSID PASSWORD【路由器相关】,username【网站账户】,password【网站密码】,CLIENT_ID【刚记录的clientID后面加个1】,TOPIC_LEDB【刚记录的TOPIC】) [mw_shl_code=python,true]from umqtt.simple import MQTTClient from machine import Pin,Timer import network import time SSID="DFROBOT_AP" PASSWORD="12345678" led=Pin(2, Pin.OUT, value=0) tim = Timer(-1) SERVER = "182.254.130.180" CLIENT_ID = "S1grx_VmNW2" TOPIC_LEDA = b"B1rl_47NZ" username='H1UGxqD4-' password='BkeLGeqvVb' def connectWifi(ssid,passwd): global wlan wlan=network.WLAN(network.STA_IF) wlan.active(True) wlan.disconnect() wlan.connect(ssid,passwd) while(wlan.ifconfig()[0]=='0.0.0.0'): time.sleep(1) connectWifi(SSID,PASSWORD) server=SERVER c = MQTTClient(CLIENT_ID, server,0,username,password) c.connect() print("Connected to %s, publish message to %s topic" % (server, TOPIC_LEDA)) try: while 1: c.publish(TOPIC_LEDA,b'on') time.sleep(3) c.publish(TOPIC_LEDA,b'off') time.sleep(3) finally: c.disconnect() [/mw_shl_code] 第五步:运行设备A程序,运行设备B程序。A每3秒向B发送一次开关指令,B的led灯不停的闪烁 |
做成了,我只用了A程序,通过网站发字符串控制灯,不过A程序的on后面的值要改成1和off后面的值要改成0,另外我没有在client_id后面加2,请问岛主,为什么要在id后面+2或者+1? |
秦皇岛岛主 发表于 2017-8-22 09:38 df物联网站id总在刷新,程序里面的id也要跟着变吗?如果不变,是不是可以随便写个数字代替id? |
© 2013-2024 Comsenz Inc. Powered by Discuz! X3.4 Licensed