Skip to content

Instantly share code, notes, and snippets.

@qoobaa
Created January 2, 2017 16:43
Show Gist options
  • Save qoobaa/d13e23a904cd29c54c6d0ee27a1eee5f to your computer and use it in GitHub Desktop.
Save qoobaa/d13e23a904cd29c54c6d0ee27a1eee5f to your computer and use it in GitHub Desktop.
SDS011 + ESP8266
DEVICE_ID="pmsensor-" .. string.format("%02X", node.chipid())
BOOT_WAIT = 3
DWEET_INTERVAL = 60
LED_PIN = 4
pm25 = nil
pm10 = nil
function led(state)
gpio.mode(LED_PIN, gpio.OUTPUT)
if state == 0 then
gpio.write(LED_PIN, gpio.HIGH)
elseif state == 1 then
gpio.write(LED_PIN, gpio.LOW)
else
if gpio.read(LED_PIN) == gpio.HIGH then
led(1)
else
led(0)
end
end
end
function dweet()
led(0)
url = "https://dweet.io/dweet/for/" .. DEVICE_ID
headers = 'Content-Type: application/json\r\n'
payload = '{"pm25":' .. pm25 .. ',"pm10":' .. pm10 .. '}'
print("Dweeting measurements: " .. payload)
http.post(
url, headers, payload,
function (code, data)
if not code == 200 then
print("Dweet failed, code: " .. code .. ", response: " .. data)
else
print("Measurements dweeted successfully: " .. data)
led(1)
end
end
)
end
function boot()
uart.setup(0, 9600, 8, uart.PARITY_NONE, uart.STOPBITS_1, 1)
uart.on(
"data", "\171",
function (data)
if string.len(data) == 10 then
header, command, pm25l, pm25h, pm10l, pm10h, id1, id2, sum, tail = struct.unpack("BBBBBBBBBB", data)
if header == 0xAA and command == 0xC0 and (pm25l + pm25h + pm10l + pm10h + id1 + id2) % 256 == sum and tail == 0xAB then
pm25 = (pm25h * 256 + pm25l) / 10
pm10 = (pm10h * 256 + pm10l) / 10
print("Received SDS011 message, PM 2.5: " .. pm25 .. ", PM 10: " .. pm10)
else
print("Malformed SDS011 message")
end
else
print("Invalid SDS011 message size")
end
end,
0
)
tmr.alarm(
0, DWEET_INTERVAL * 1000, tmr.ALARM_AUTO,
function ()
if pm25 and pm10 then
dweet()
end
end
)
end
function setup()
tmr.alarm(
0, 100, tmr.ALARM_AUTO,
function ()
led()
end
)
enduser_setup.start(
function()
tmr.unregister(0)
led(1)
boot()
end,
function(err, str)
print("enduser_setup: Error #" .. err .. ": " .. str)
end
);
end
tmr.alarm(0, BOOT_WAIT * 1000, tmr.ALARM_SINGLE, setup)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment