写一段基于dht11使用blinker显示温湿度的代码
时间: 2023-06-06 16:06:44 浏览: 229
好的,以下是基于dht11使用blinker显示温湿度的代码:
```python
import dht
import machine
from machine import Pin
from time import sleep
from umqtt.simple import MQTTClient
import json
import network
import urequests
import ujson
import uos
import utime
import blinker
auth = {'username':'user1', 'password':'123456'}
client_id = 'esp8266_' + uos.environ['NODEMCU_CHIPID']
mqtt_host = 'mqtt.blinker.cc'
mqtt_port = 1883
mqtt_client = MQTTClient(client_id, mqtt_host, mqtt_port, auth=auth)
d = dht.DHT11(machine.Pin(4))
def read_sensor_data():
d.measure()
temp = d.temperature()
humidity = d.humidity()
return temp, humidity
def main():
try:
while True:
temp, humidity = read_sensor_data()
utc_now = utime.time()
# 构建数据上报的数据
data = { "temp": temp, "hum": humidity, "time": utc_now }
# 上报数据到 Blinker 云平台
mqtt_client.connect()
mqtt_client.publish('user1/#', json.dumps(data))
mqtt_client.disconnect()
print('Temp: {} C, Humidity: {} %'.format(temp, humidity))
sleep(10)
except Exception as e:
print('Error:', e)
if __name__ == '__main__':
main()
```
阅读全文