Created
March 28, 2016 11:06
-
-
Save chaosong/93e5a641ff403b836f34 to your computer and use it in GitHub Desktop.
nodemcu read dht22 and pms5003
This file contains hidden or 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
function initWIFI() | |
print("Setting up WIFI...") | |
wifi.setmode(wifi.STATION) | |
wifi.sta.config("<wifi-id>", "<wifi-password>") | |
wifi.sta.connect() | |
tmr.alarm(1, 1000, 1, | |
function() | |
if wifi.sta.getip()== nil then | |
print("IP unavailable, Waiting...") | |
else | |
tmr.stop(1) | |
print("Config done, IP is "..wifi.sta.getip()) | |
end | |
end -- function | |
) | |
end -- initWIFI | |
function initUDP() | |
-- setup UDP port | |
cu = net.createConnection(net.UDP) | |
cu:connect(55555, "192.168.18.163") | |
end -- initUDP | |
function parse(data) | |
local bs = {} | |
for i = 1, #data do | |
bs[i] = string.byte(data, i) | |
end | |
if (bs[1] ~= 0x42) or (bs[2] ~= 0x4d) then | |
return nil | |
end | |
local d = {} | |
d['pm1_0-CF1-ST'] = bs[5] * 256 + bs[6] | |
d['pm2_5-CF1-ST'] = bs[7] * 256 + bs[8] | |
d['pm10-CF1-ST'] = bs[9] * 256 + bs[10] | |
d['pm1_0-AT'] = bs[11] * 256 + bs[12] | |
d['pm2_5-AT'] = bs[13] * 256 + bs[14] | |
d['pm10-AT'] = bs[15] * 256 + bs[16] | |
d['0_3um-count'] = bs[17] * 256 + bs[18] | |
d['0_5um-count'] = bs[19] * 256 + bs[20] | |
d['1_0um-count'] = bs[21] * 256 + bs[22] | |
d['2_5um-count'] = bs[23] * 256 + bs[24] | |
d['5_0um-count'] = bs[25] * 256 + bs[26] | |
d['10um-count'] = bs[27] * 256 + bs[28] | |
return d | |
end -- parse | |
function serilize(t) | |
ret = '' | |
if t == nil then | |
return ret | |
end | |
for k, v in pairs(t) do | |
ret = ret .. k .. ':' .. v .. ',' | |
end | |
if #ret > 0 then | |
ret = string.sub(ret, 0, -2) | |
end | |
return ret | |
end --serilize | |
function report() | |
status, temp, humi, temp_dec, humi_dec = dht.readxx(pin) | |
if status == dht.OK then | |
-- Float firmware using this example | |
print("DHT Temperature:"..temp..";".."Humidity:"..humi) | |
cu:send('env,temp:' .. temp .. ',humi:' .. humi) | |
elseif status == dht.ERROR_CHECKSUM then | |
print( "DHT Checksum error." ) | |
elseif status == dht.ERROR_TIMEOUT then | |
print( "DHT timed out." ) | |
end | |
if aqi ~= nil then | |
cu:send('aqi,' .. serilize(aqi)) | |
end | |
end -- report | |
initWIFI() | |
initUDP() | |
aqi = nil | |
dht = require('dht') | |
pin = 4 | |
uart.setup(0, 9600, 8, 0, 1, 0) | |
uart.on("data", 32, | |
function(data) | |
aqi = parse(data) | |
if aqi == nil then | |
return | |
end | |
end, 0) | |
print('hello') | |
tmr.alarm(0, 10000, 1, report) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment