Created
February 5, 2019 12:51
-
-
Save smashnet/94302578e3afae84e34782eebcd24a9d to your computer and use it in GitHub Desktop.
NodeMCU with regular BMP280 readouts and webserver for JSON delivery
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
-- I assume that wifi is successfully initialized and that we have an IP already! | |
-- Init BMP280 sensor | |
altitude_measurement_location = 160 | |
sda, scl = 6, 5 | |
i2c.setup(0, sda, scl, i2c.SLOW) | |
mode = bme280.setup(nil, nil, nil, 0) | |
-- mode = 1 -> BMP280 | |
-- mode = 2 -> BME280 | |
-- Callback function to process sensor readings | |
bmp280_readings_available_event = function() | |
T, P, H, QNH = bme280.read(altitude_measurement_location) | |
Tsgn = (T < 0 and -1 or 1); T = Tsgn*T | |
D = bme280.dewpoint(H, T) | |
Dsgn = (D < 0 and -1 or 1); D = Dsgn*D | |
print("New sensor readout available, check variables: T, P, H, QNH, D") | |
print("For a neat JSON object with current values do a GET request on {node_IP}:80/") | |
end | |
-- Do an initial readout to have some values in case someone requests them | |
bme280.startreadout(0, bmp280_readings_available_event) | |
-- Create timer to read BMP280 every 30 seconds | |
bmp280timer = tmr.create() | |
bmp280timer:register(30000, tmr.ALARM_AUTO, function() | |
-- Read current values from sensor | |
bme280.startreadout(0, bmp280_readings_available_event) | |
end) | |
bmp280timer:start() | |
-- Start a simple webserver to serve the values in a neat JSON object | |
srv=net.createServer(net.TCP) | |
srv:listen(80,function(conn) | |
conn:on("receive", function(sck,request) | |
local json = "{"; | |
json = json.."\"nodeid\": "..node.chipid()..", "; | |
json = json.."\"sensors\": {"; | |
json = json.."\"bmp280\": {"; | |
json = json.."\"temperatur\": "..string.format("%s%d.%02d", Tsgn<0 and "-" or "", T/100, T%100)..", "; | |
json = json.."\"pressure\": "..string.format("%d.%03d", P/1000, P%1000)..", "; | |
json = json.."\"pressure_sea\": "..string.format("%d.%03d", QNH/1000, QNH%1000)..", "; | |
json = json.."\"humidity\": "..string.format("%d.%03d", H/1000, H%1000)..", "; | |
json = json.."\"dew_point\": "..string.format("%s%d.%02d", Dsgn<0 and "-" or "", D/100, D%100); | |
json = json.."}"; | |
json = json.."}"; | |
json = json.."}"; | |
sck:send("HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n"); | |
sck:send(json); | |
collectgarbage(); | |
end) | |
conn:on("sent", function(sck) sck:close() end) | |
end) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment