Skip to content

Instantly share code, notes, and snippets.

@karlp
Last active June 30, 2016 14:09
Show Gist options
  • Save karlp/0659315b05bb6663edd79d1035a0fe41 to your computer and use it in GitHub Desktop.
Save karlp/0659315b05bb6663edd79d1035a0fe41 to your computer and use it in GitHub Desktop.
Publish DHT22 to MQTT on an ESP8266 (wemos D1 mini)
-- DHT22 to MQTT Publisher
-- Andrew Elwell, 2016-06-08
client='ESP-'..node.chipid()
m = mqtt.Client(client, 60)
m:lwt("status/"..client, "offline", 0, 1)
m:connect("10.1.1.251", 1883, 0, 1, function(hohoho)
print("connected")
hohoho:publish(string.format("status/%s", client, 0, 1))
end,
function (anothername, reason)
print("failed reason", reason)
end
)
function readDHT()
-- Read Temp from DHT22 on pin 4
status, temp, humi, temp_dec, humi_dec = dht.read(4)
if status == dht.OK then
payload = ('{ "temp": '..temp..', "humidity": '..humi..' }')
print(payload)
m:publish('sensors/'..client..'/json', payload,0,0)
elseif status == dht.ERROR_CHECKSUM then
print( "DHT Checksum error." )
elseif status == dht.ERROR_TIMEOUT then
print( "DHT timed out." )
end
end
tmr.alarm(0, 3000, tmr.ALARM_AUTO, function() readDHT(); end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment