本帖最后由 kylinpoet 于 2023-9-6 12:54 编辑
一、固件更新
1. 首先说明下,产品维库给出的固件下载地址错误,麻烦小编更新下:
https://wiki.dfrobot.com.cn/_SKU_DFR0975_FireBeetle_2_Board_ESP32_S3#target_10
正确地址应该是这个:
https://micropython.org/download/ESP32_GENERIC_S3/
按照教程输入固件后,也使用维库里推荐的 thonny,查看下版本:
我们输入例程后:板子上的灯已经成功点亮了:
- import time
- from machine import Pin
-
- led=Pin(21,Pin.OUT)
-
- while True:
- led.value(1)
- time.sleep(1)
- led.value(0)
- time.sleep(1)
复制代码
照例,我们利用板上自带的 GPIO47 按钮来做个开关:
- import time
- from machine import Pin
-
- button_pressed = False # global variable
- pin_button = Pin(47, mode=Pin.IN, pull=Pin.PULL_UP)
- pin_led = Pin(21, Pin.OUT)
- pin_led.value(0)
-
- def button_isr(pin):
- global button_pressed
- button_pressed = not button_pressed
- print(button_pressed)
-
-
- if __name__ == "__main__":
- pin_button.irq(trigger=Pin.IRQ_RISING,handler=button_isr)
- while True:
- pin_led.value(button_pressed)
- time.sleep(0.01)
复制代码
使用系统中断来控制开与关。
二、天气应用
有wifi的地方,就有天气,就像有主板的地方就有LED。
我们使用 esp32,来获取下今日天气,因为维库里没有MicroPython的使用例程,我们手搓一个:
- import time
- from machine import Pin
-
- import network
- import urequests
- import ujson
-
-
- def connectWiFi(ssid, passwd):
- wlan=network.WLAN(network.STA_IF)
- wlan.active(True)
- wlan.disconnect()
- wlan.connect(ssid, passwd)
- j = 0
- while(wlan.ifconfig()[0]=='0.0.0.0'):
- time.sleep(1)
复制代码
完美解析!
三、关于MQTT
要在esp32上使用MQTT,我们需要导入两个文件:simple.py 和 robust.py 文件,用于连接mqtt,为了节约篇幅,作为附件附上。具体使用可参考:
https://github.com/micropython/micropython-lib/blob/master/micropython/umqtt.robust/umqtt/robust.py
照例,我们使用 DF 的 iot平台:
写入代码:
# main.py
import time
import network
from machine import Pin
from robust import MQTTClient
clientID = "ESP32" #连接ID
server = "iot.dfrobot.com.cn" #MQTT服务器地址
port = 1883 #MQTT服务器端口号
userName = "***" #MQTT登录用户名
passWord = "***" #MQTT登录密码
keepAlive = 60 #心跳周期
wifiSSID = "**4-2" #WIFI SSID
wifiPassWord = "x" #WIFI密码
subTopic = "Q-**" #订阅的主题
pubTopic = "subTopic" #发布的主题
num = 0
pinled=Pin(21,Pin.OUT)
#连接WLAN
def wifiConnect():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print("开始连接...")
wlan.connect(wifiSSID, wifiPassWord)
i = 1
while not wlan.isconnected():
print("正在连接中...".format(i))
i += 1
time.sleep(1)
print("网络信息为:", wlan.ifconfig())
#订阅主题回调函数 收到消息时在此处理
def subCallBack(subTopic, msg):
global pinled
global num
print(subTopic, msg)
msg = msg.decode().lower()
print(msg)
if msg == 'off':
pinled.value(0)
elif msg == 'on':
pinled.value(1)
# num=num+1
# mqtt.publish(pubTopic,str(num)) #推送消息至发布的主题
wifiConnect()
mqtt = MQTTClient(clientID,server,port,userName,passWord,keepAlive)
mqtt.set_callback(subCallBack)
mqtt.connect()
mqtt.subscribe(subTopic)
print("订阅成功")
while True:
mqtt.check_msg()
time.sleep(0.1)
效果视频,就是mqtt的普通视频,这里就不演示了。
四、总结
就问你心不心动?DF商城走起!
|