Skip to content

Instantly share code, notes, and snippets.

@Tomin1
Last active October 18, 2018 14:39
Show Gist options
  • Select an option

  • Save Tomin1/c5893d4a4e80de7f00c2ecd1b6600390 to your computer and use it in GitHub Desktop.

Select an option

Save Tomin1/c5893d4a4e80de7f00c2ecd1b6600390 to your computer and use it in GitHub Desktop.
NodeMCU DS18B20 station
-- Use this to configure NodeMCU to connect your AP
local STATION_CONFIG = {}
STATION_CONFIG.ssid = "my ssid"
STATION_CONFIG.pwd = "my password"
STATION_CONFIG.auto = true
STATION_CONFIG.save = true
wifi.setmode(wifi.STATION)
wifi.sta.config(STATION_CONFIG)
wifi.sta.connect()
-- Requires ds18b20 and ow modules
local OW_BUS_PIN = 3
local RES = 10
local PORT = 80
local HEADER = "HTTP/1.1 200 OK\nContent-Type: text/plain; charset=utf-8\n\n"
local ERROR_400 = "HTTP/1.1 400 Bad Request\n\n"
local ERROR_404 = "HTTP/1.1 404 Not Found\n\n"
local function addr2string(addr)
return string.format("%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X",
string.byte(addr, 1), string.byte(addr, 2), string.byte(addr, 3),
string.byte(addr, 4), string.byte(addr, 5), string.byte(addr, 6),
string.byte(addr, 7), string.byte(addr, 8))
end
local function find(f_addr)
ow.reset_search(OW_BUS_PIN);
ow.target_search(OW_BUS_PIN, tonumber(string.sub(f_addr, 1, 2)));
local s_addr = nil
repeat
s_addr = ow.search(OW_BUS_PIN)
if s_addr ~= nil then
s_addr = addr2string(s_addr)
end
until s_addr == nil or s_addr == f_addr
return s_addr ~= nil and s_addr == f_addr
end
local function setup()
local addrs = {}
local count = 0;
ds18b20.setup(OW_BUS_PIN)
ow.reset_search(OW_BUS_PIN);
ow.target_search(OW_BUS_PIN, 0x28);
local addr = ow.search(OW_BUS_PIN);
while addr ~= nil do
count = count + 1
addrs[count] = addr2string(addr)
addr = ow.search(OW_BUS_PIN)
end
ds18b20.setting(addrs, RES)
end
local function close(conn) conn:close() end
local function receiver(sck, data)
local path = string.match(data, "GET ([^ ]+) HTTP.*")
if path == nil then
sck:send(ERROR_400, close)
else if path == "/" then
ow.reset_search(OW_BUS_PIN)
sck:send(HEADER, function(conn)
local addr = ow.search(OW_BUS_PIN)
if addr ~= nil then
conn:send(addr2string(addr) .. "\n")
else
conn:close()
end
end)
else
local addr = string.match(path, "/(%x+:%x+:%x+:%x+:%x+:%x+:%x+:%x+)")
if addr == nil then
sck:send(ERROR_404, close)
else
if not find(addr) then
sck:send(ERROR_404, close)
else
ds18b20.read(function(index, rom, res, temp, temp_dec, par)
sck:send(HEADER .. string.format("%f°C\n", temp), close)
end, {addr})
end
end
end end
end
setup()
local srv = net.createServer(net.TCP)
srv:listen(PORT, function(conn) conn:on("receive", receiver) end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment