Instantly share code, notes, and snippets.

Embed
What would you like to do?
from time import sleep
from umqtt.simple import MQTTClient
from machine import Pin
from dht import DHT22
SERVER ='m11.cloudmqtt.com'
CLIENT_ID='ESP32_TH'
PORT=12637
TOPIC=b'temp_humidity'
client=MQTTClient(CLIENT_ID,SERVER,PORT,"cloudmqttusername","cloudmqqttpassword")
client.connect()
sensor=DHT22(Pin(13,Pin.IN,Pin.PULL_UP))
while True:
try:
sensor.measure()
t = sensor.temperature()
h = sensor.humidity()
if isinstance(t, float) and isinstance(h, float):
msg = (b'{0:3.1f},{1:3.1f}'.format(t,h))
client.publish(TOPIC,msg)
print(msg)
else:
print('invalid sensor value')
except OSError:
print ('failed to read sensor')
sleep(4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment