ESP8266 ESP01 temperature logger to thingspeak template

nodemcu with ds18b20 support
two files: init.lua (attached) and par.txt (attached, configure for your roter/thingspeak channel)

In case you need to change init.lua, reset the esp8266 and quickly execute: file.remove("par.txt")
--- file par.txt ---
router_ssid
route_pass
manual_ip
manual_gateway
api_key_thingspeak
Order: ssid,pass,ipman,gwman,apikey

-- file: init.lua --
if file.open("par.txt","r") then
ssid=string.gsub(file.readline(), "\n", "")
pass=string.gsub(file.readline(), "\n", "")
ipman=string.gsub(file.readline(), "\n", "")
gwman=string.gsub(file.readline(), "\n", "")
apikey=string.gsub(file.readline(), "\n", "")

  file.close()

wifi.setmode(wifi.STATION)
wifi.sta.setip({ip=ipman,netmask="255.255.255.0",gateway="192.168.1.1"})

station_cfg={}
station_cfg.ssid=ssid
station_cfg.pwd=pass

station_cfg.auto=false
wifi.sta.config(station_cfg)
wifi.sta.connect()
ds18b20.setup(3)

t11=20
ds18b20.read( function(ind,rom,res,temp,tdec,par)
    t11=temp
    end,{});
function senddata(ip)
v11= string.format("%.02f",t11) 
print("T="..v11.." ip="..ip)


conn=net.createConnection(net.TCP, 0) 
conn:on("receive", function(conn, payload) print(payload) end)
conn:connect(80,ip) 

str="GET /update?api_key="..apikey.."&field1="..v11
        .. "\r\nHTTP/1.1\r\nHost: api.thingspeak.com\r\n"
        .. "Connection: close\r\nAccept: */*\r\n"
        .. "User-Agent: Mozilla/4.0 (compatible; esp8266 Lua; Windows NT 5.1)\r\n\r\n"

conn:send(str)
conn:on("sent",function(conn)  

 print("sent and sleeping now")
 conn:close()
 node.dsleep(300*1000000) 
  end)
end

wifi.eventmon.register(wifi.eventmon.STA_CONNECTED, function(T)
print("connected")

-- dns and senddata
net.dns.setdnsserver("8.8.8.8", 0)
net.dns.resolve("api.thingspeak.com", function(sk, ip)
    if (ip == nil) then 
    senddata('52.5.13.84') ; else  senddata(ip); end
end)
end)

mytimer = tmr.create()
mytimer:register(10000, tmr.ALARM_SINGLE, function() 
print("sleep because not connected")
node.dsleep(300*1000000)  end)
if not mytimer:start() then print("uh oh") end
end

<< Volver a la página anterior