Created
October 11, 2020 23:46
-
-
Save nevercast/482b56b074046fdebf76c5053a564084 to your computer and use it in GitHub Desktop.
Simple DHT11 read and publish to AIO
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import machine, network, time, dht, mqtt | |
# mqtt: https://github.com/micropython/micropython-lib/blob/master/umqtt.simple/umqtt/simple.py | |
## SECRETS | |
WIFI_NAME='<WIFI SSID>' | |
WIFI_PASS='<WIFI PASSWORD>' | |
MQTT_HOST='io.adafruit.com' | |
MQTT_PORT=1883 | |
MQTT_USER='<ADAFRUIT USERNAME>' | |
MQTT_PASS='<ADAFRUIT IO KEY>' | |
MQTT_ALIVE_TOPIC='<ADAFRUIT USERNAME>/feeds/sensors.is-online' | |
MQTT_DHT11_TOPIC='<ADAFRUIT USERNAME>/feeds/sensors.temperature' | |
SAMPLE_INTERVAL=5 # Seconds between reading the sensor | |
# Create the DHT11 driver to talk to the sensor on Pin 4 | |
dht11 = dht.DHT11(machine.Pin(4)) | |
# Connect to the WiFi | |
wifi = network.WLAN(network.STA_IF) | |
wifi.active(True) | |
wifi.connect(WIFI_NAME, WIFI_PASS) | |
while not wifi.isconnected(): | |
print('Waiting for WiFi to connect...') | |
time.sleep(1) | |
print('Connecting to MQTT...') | |
# Create MQTT Client | |
client = mqtt.MQTTClient('dht11_sensor_client_name', MQTT_HOST, port=MQTT_PORT, user=MQTT_USER, password=MQTT_PASS) | |
client.connect() | |
# We set the Last Will and Testament, which is an MQTT feature that creates a published message on the server when | |
# our device loses connection with the server. We can use this to send a disconnected message. | |
client.set_last_will(topic=MQTT_ALIVE_TOPIC, msg='False') | |
# Send a message saying we are alive | |
client.publish(topic=MQTT_ALIVE_TOPIC, msg='True') | |
last_two_readings=[] | |
while True: | |
time.sleep(SAMPLE_INTERVAL) | |
print('Sampling...') | |
reading = dht11.temperature() | |
if reading not in last_two_readings: | |
print('Sending new value...') | |
# Append the reading | |
last_two_readings.append(reading) | |
# Remove any older readings (three or more) | |
last_two_readings = last_two_readings[-2:] | |
# Send the new value to the server | |
client.publish(topic=MQTT_DHT11_TOPIC, msg=str(reading)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment