Created
January 27, 2018 18:19
-
-
Save enlavin/e8d26cf5ded93f1edcb0c08fc830f1a8 to your computer and use it in GitHub Desktop.
Publish temperature and humidity to a MQTT topic using a NodeMCU + Micropython and a DHT11
This file contains 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 dht | |
import machine | |
import network | |
import utime | |
from umqtt.simple import MQTTClient | |
NODEMCU_PINS = (16, 5, 4, 0, 2, 14, 12, 13, 15, 3, 1, 9, 10) | |
d = dht.DHT11(machine.Pin(NODEMCU_PINS[4])) | |
sta_if = network.WLAN(network.STA_IF) | |
while True: | |
if not sta_if.isconnected(): | |
print('Connecting to WiFi...') | |
sta_if.active(True) | |
sta_if.connect('essid', 'password') | |
while not sta_if.isconnected(): | |
utime.sleep(1) | |
print('Connecting to MQTT server...') | |
c = MQTTClient("unique-client-id", "mqtt-server-addr", user="user", password="password") | |
c.connect() | |
d.measure() | |
print('Publishing sensors...') | |
c.publish("node/temp", str(d.temperature()), retain=True, qos=1) | |
c.publish("node/hum", str(d.humidity()), retain=True, qos=1) | |
c.disconnect() | |
utime.sleep(5) | |
rtc = machine.RTC() | |
rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP) | |
rtc.alarm(rtc.ALARM0, 60000) | |
print('Zzzzz...') | |
machine.deepsleep() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment