import time
from machine import Pin,PWM,ADC # ---- 添加 --------
import network
from umqtt.simple import MQTTClient
import dht
def do_connect():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('connecting to network...')
wlan.connect('123456', '123456789')
i = 1
while not wlan.isconnected():
print("正在链接...{}".format(i))
i += 1
time.sleep(1)
print('network config:', wlan.ifconfig())
def sub_cb(topic, msg): # 回调函数,收到服务器消息后会调用这个函数
print(topic, msg)
# ---- 添加 --------
if topic.decode("utf-8") == "ledctl" and msg.decode("utf-8") == "on":
led_pin.value(1)
elif topic.decode("utf-8") == "ledctl" and msg.decode("utf-8") == "off":
led_pin.value(0)
# ---- 添加 --------
if topic.decode("utf-8") == "motor" and msg.decode("utf-8") == "on":
motor1_pin.value(1) and motor2_pin.value(0)
elif topic.decode("utf-8") == "motor" and msg.decode("utf-8") == "off":
motor1_pin.value(0) and motor2_pin.value(1)
# if topic.decode("utf-8") == "duoji" and msg.decode("utf-8") == "on":
# p2.duty_u16(4915)
# elif topic.decode("utf-8") == "duoji" and msg.decode("utf-8") == "off":
# p2.duty_u16(1638)
if topic.decode("utf-8") == "temp" and msg.decode("utf-8") >"28":
motor1_pin.value(1) and motor2_pin.value(0)
if topic.decode("utf-8") == "temp" and msg.decode("utf-8") <"27":
motor1_pin.value(0) and motor2_pin.value(1)
# 1. 联网
do_connect()
# 2. 创建mqt
c = MQTTClient("umqtt_client", "121.196.235.103") # 建立一个MQTT客户端
c.set_callback(sub_cb) # 设置回调函数
c.connect() # 建立连接
c.subscribe(b"ledctl") # 监控ledctl这个通道,接收控制命令
c.subscribe(b"motor") # 监控motor这个通道,接收控制命令
c.subscribe(b"temp") # 监控temp这个通道,接收控制命令
c.subscribe(b"mq") # 监控temp这个通道,接收控制命令
# ---- 添加 --------
# 3. 创建控件对应Pin对象
led_pin = Pin(2, Pin.OUT)
p2 = PWM(Pin(32))
motor1_pin = Pin(18,Pin.OUT)
motor2_pin = Pin(19,Pin.OUT)
sensor = dht.DHT11(Pin(22))
# 模拟量
ps2_y = ADC(Pin(34))
ps2_y.atten(ADC.ATTN_11DB) # 这里配置测量量程为3.3V
# 数字量
p15 = Pin(15, Pin.IN)
# ---- 添加 --------
while True:
c.check_msg()
sensor.measure()
val_y = ps2_y.read() # 0-4095
light = p15.value() # 1为没有危险气体,0为有危险气体。
data = "temp(c): %s℃ humidity: %sRH val_y: %s light: %s" % (sensor.temperature(), sensor.humidity(),val_y,light)
c.publish('temp',str(sensor.temperature()),qos =0)#上传温度
c.publish('humid',str(sensor.humidity()),qos =0)#上传湿度
# c.publish('val_y',str(val_y()),qos =0)#上传湿度
c.publish('val_y',str(val_y),qos =0)#上传湿度
c.publish('light',str(light),qos =0)
print(data)
time.sleep(1)
if light == 0:
print("检测到危险气体,请远离!")