Instantly share code, notes, and snippets.

Embed
What would you like to do?
IoT Sensor with NodeMCU & BME280 in Lua for blog.alexellis.io
-- Copyright Alex Ellis 2018
-- License MIT
local mySsid="SSID"
local myKey="WPA_PASSWORD"
function connect_wifi(ssid, key)
wifi.setmode(wifi.STATION)
wifi.sta.config(ssid,key)
wifi.sta.connect()
tmr.delay(1000000)
end
function wait_ip()
print("Waiting for IP")
local max=15
while(wifi.sta.getip() == nil)
do
max=max-1
tmr.delay(1000000)
print(string.format('WiFi attempt %d', max))
if max==0 then
return
end
end
print("Waited for IP")
print(wifi.sta.getip())
end
connect_wifi(mySsid,myKey)
wait_ip()
brokerHost="test.mosquitto.org"
interval=15000
mytimer = tmr.create()
mytimer:register(interval, tmr.ALARM_AUTO, function()
m = mqtt.Client("nodemcu", 120)
m:connect(brokerHost, 1883, 0, function(client)
print(string.format("Connected to broker: %s",brokerHost))
sda, scl = 3, 4
mode = bme280.init(sda, scl)
print(mode)
tmr.delay(1000000)
H, T = bme280.humi()
t = T / 100
h = H / 1000
ip = wifi.sta.getip()
if ip == nil then
ip = "127.0.0.1"
end
vdd33=adc.readvdd33()
RSSI=wifi.sta.getrssi()
if RSSI == nil then
RSSI=-1
end
msg = string.format('{"sensor": "s1", "humidity": "%.2f", "temp": "%.3f", "ip": "%s", "vdd33": "%d", "rssi": %d}', h, t, ip, vdd33, RSSI)
print(msg)
client:publish("sensor-readings", msg, 0, 0, function(client) print("sent") end)
m:close()
end, function(client, reason)
print("failed reason", reason)
end)
end)
tmr.start(mytimer)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment