import network
from umqtt.simple import MQTTClient
from machine import Pin, ADC
import time
# 设置WiFi连接信息
WIFI_SSID = "maker"
WIFI_PASSWORD = "qazwsx12"
# 设置MQTT连接信息
MQTT_SERVER = "broker.emqx.io"
MQTT_PORT = 1883
MQTT_USER = "zoudingrong"
MQTT_PASSWORD = "sfsf"
MQTT_TOPIC = "topic/analog"
adc = ADC(Pin(34))
# 连接WiFi网络
station = network.WLAN(network.STA_IF)
station.active(True)
station.connect(WIFI_SSID, WIFI_PASSWORD)
while not station.isconnected():
pass
print('Network connected:', station.ifconfig())
# 创建MQTT客户端
client = MQTTClient("esp32", MQTT_SERVER, MQTT_PORT, MQTT_USER, MQTT_PASSWORD,keepalive=60)
# 连接MQTT服务器
client.connect()
# 创建ADC对象并读取模拟信号
while True:
try:
value = adc.read()//20
print('value',value)
message= '{"light":"12","sound":'+str(value)+',"weather":"qing,23,1","time":"12:12:11"}'
#client.publish(TOPIC, message)
# 将模拟信号作为MQTT消息发布到指定主题
client.publish(MQTT_TOPIC, str(message), retain=True)
except:
print('error')
client.disconnect()
time.sleep(1)
# 断开MQTT连接
micropython mqtt 发送模拟信号
最新推荐文章于 2023-11-14 18:10:47 发布