Created
January 10, 2018 06:07
-
-
Save wbchn/4161b864602e2f1c1ad7613118c042b1 to your computer and use it in GitHub Desktop.
NodeMCU init.lua, from https://www.ibm.com/developerworks/cn/iot/library/iot-mqtt-nodemcu-monitor-air-quality/index.html
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
-- 1.Setup the device ID and access credential.See later. | |
-- PIN assignment | |
-- D5 is the driver PIN for the dust detector | |
dpin = 5 | |
-- D0 is the LED on the NodeMCU board | |
lpin = 0 | |
gpio.mode(dpin, gpio.INT) | |
-- The current pulse params | |
rising_ts = 0 | |
falling_ts = 0 | |
-- aggregated timing vars | |
high_time = 0 | |
low_time = 0 | |
-- determine if the INT is legit | |
prev_level = -1 | |
-- setup Wifi | |
wifi.setmode(wifi.STATION) | |
wifi.sta.config("SSID","password") | |
wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, connected) | |
-- This is the main application loop | |
-- It starts after the network is up | |
function connected (e) | |
-- 2.Connect to the MQTT service.See later. | |
-- Timer to take a measurement and send data | |
-- every 10 minutes. | |
tmr.alarm(1, 600000, tmr.ALARM_AUTO, function() | |
-- Trigger the “dpin_cb” function (defined below) | |
-- when a pulse comes in. | |
-- dpin_cb will turn off the trigger after 30s | |
gpio.trig(dpin, "both", dpin_cb) | |
end) | |
end | |
-- Define the INT callback function | |
function dpin_cb (level, when) | |
-- current_level = gpio.read(dpin) | |
if prev_level == level then | |
-- there is no change. ignore | |
return | |
else | |
prev_level = level | |
end | |
if level == 1 then | |
rising_ts = tmr.now() | |
print ("raising edge : " .. rising_ts) | |
-- turn on the red LED | |
gpio.write(lpin, gpio.LOW) | |
else | |
falling_ts = tmr.now() | |
print ("falling edge : " .. falling_ts) | |
-- turn off the red LED | |
gpio.write(lpin, gpio.HIGH) | |
end | |
-- Start aggregated timer after a complete pulse is detected | |
if falling_ts > 0 and rising_ts > 0 then | |
if falling_ts > rising_ts then | |
high_time = high_time + falling_ts - rising_ts | |
else | |
low_time = low_time + rising_ts - falling_ts | |
end | |
end | |
-- Sampling period is 30*1,000,000 macroseconds | |
total_time = high_time + low_time | |
if total_time > 30000000 then | |
lpo = low_time / total_time | |
-- remove the INT and reset timers | |
gpio.trig(dpin, "none") | |
rising_ts = 0 | |
falling_ts = 0 | |
high_time = 0 | |
low_time = 0 | |
-- turn off the red LED | |
gpio.write(lpin, gpio.HIGH) | |
-- Very rough estimate.More calibration needed | |
pm25 = lpo * 100.0 * 1.5 | |
-- 3.Send data to the MQTT server.See later. | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment