from umqtt.simple import MQTTClient
from machine import Pin
import machine, time, math
import micropython
from machine import Timer #使用定时器定时读取温湿度
import dht
import ujson
import ssd1306
from machine import I2C
#屏幕设置
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
# 选择温湿度引脚
led_blue = machine.PWM(machine.Pin(2), freq=1000) # 设置 GPIO2 为输出
led_blue.duty(1023)
sensor=dht.DHT11(machine.Pin(5))
# MQTT服务器地址域名为:49.235.173.142,不变
SERVER = "broker.mqttdashboard.com"
# 设备ID
CLIENT_ID = "pwmled_lianglizhi32"
# 随便起个名字
TOPIC1 = b"ledctl2111605123"
TOPIC2 = b"pwmled2111605123"
TOPIC3 = b"ledstatus2111605123"
TOPIC4 = b"sensor2111605123"
TOPIC5 = b"led2111605123"
username = "123123"
password = "321321"
pwm_old = 0
pwmval = 0
c = None
#wifi连接
def do_connect():
import network
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('Wokwi-GUEST', '') #wifi的SSID和密码
while not sta_if.isconnected():
pass
print('network config:', sta_if.ifconfig())
do_connect()
#定义读取温湿度的回调函数
def readTempSensor(v):
global sensor,c
sensor.measure()
#屏幕显示
oled.init_display()
oled.text('lianglizhi', 10, 10) #名字拼音
oled.text(('temp:%s'%(sensor.temperature())), 10, 20)
oled.text(('humi:%s'%(sensor.humidity())), 10, 30)
oled.show()
message = ujson.dumps({
"temp": sensor.temperature(),
"humidity": sensor.humidity(),
"help": help_btn.value(),
})
print(message)
if(c!=None):
c.publish(TOPIC4, message) #温湿度数据发送到mqtt服务器上
def delay(t):
for i in range(t):
k = 0;
#使用中断办法来调用发送求救信息函数
#把falsh按钮定义为一键求救按钮,该按钮使用gpio0端口
help_btn=Pin(0,Pin.IN)
btn_value = 1
counter=0 #表示求救次数
def btn_func(v):
global value, counter
counter += 1
btn_value =help_btn.value()+1
help_btn.value()
print("IRQ,help me!", counter,'btn_level',btn_value)
help_btn.irq(trigger=Pin.IRQ_FALLING, handler=btn_func)
def sub_cb(topic, msg):
global pwm_old, pwmval
if topic == TOPIC1:
print((topic, msg))
if msg == b"off":
pwmval = 0
elif msg == b"on":
led_blue.duty(1023)
pwmval = 1023;
if topic == TOPIC2:
pwmval = int((int(msg) / 100) * 1023)
print((topic, pwmval))
def main(server=SERVER):
global c
c = MQTTClient(CLIENT_ID, server)
c.set_callback(sub_cb)
c.connect()
c.subscribe(TOPIC1)
c.subscribe(TOPIC2)
print("Connected to %s, subscribed to %s topic" % (server, TOPIC1))
tim=Timer(-1) #创建定时器
tim.init(period=3000,mode=Timer.PERIODIC,callback=readTempSensor)
try:
while 1:
c.wait_msg()
global pwm_old, pwmval
if pwmval == 1023:
c.publish(TOPIC3, 'ledon')
elif pwmval < 1023:
c.publish(TOPIC3, 'ledoff');
if pwmval > pwm_old:
for i in range(pwm_old, pwmval, 1):
led_blue.duty(i)
delay(30)
elif pwmval < pwm_old:
for i in range(pwm_old, pwmval, -1):
led_blue.duty(i)
delay(30)
pwm_old = pwmval
finally:
c.disconnect()