Skip to content

Instantly share code, notes, and snippets.

@robinfang
Created July 28, 2019 10:50
Show Gist options
  • Select an option

  • Save robinfang/da650f87396240260e04c2d0d65e9bc2 to your computer and use it in GitHub Desktop.

Select an option

Save robinfang/da650f87396240260e04c2d0d65e9bc2 to your computer and use it in GitHub Desktop.
nodemcu+dht22测温度
function getdht()
status, temp, humi, temp_dec, humi_dec = dht.read(4)
if status == dht.OK then
print("temperature=" .. (temp) .. ", humidity=" .. (humi) .. "")
-- send message
msg = "温度" .. (temp) .. ",湿度" .. (humi) .. ""
elseif status == dht.ERROR_CHECKSUM then
print("DHT Checksum error.")
elseif status == dht.ERROR_TIMEOUT then
print("DHT timed out.")
msg = "DHT timed out."
end
return msg
end
local function sendprint(conn, data, callback)
print("sending: "..data.."")
conn:send(data, callback)
end
function run()
srv = net.createServer(net.TCP, 30)
srv:listen(80, function(conn)
conn:on("receive", function(conn, payload)
print(payload)
data = "HTTP/1.0 200 OK\r\nServer: NodeMCU on ESP8266\r\nContent-Type: text/html\r\n\r\n"..getdht() .. "\r\n"
sendprint(conn, data, function()
conn:close()
end)
end)
end)
end
function connect()
print("Connecting to WiFi access point...")
wifi.setmode(wifi.STATION)
wifi_cfg = {}
wifi_cfg.ssid = "ssid"
wifi_cfg.pwd = "password"
wifi_cfg.save = false
wifi.sta.config(wifi_cfg)
tmr.create():alarm(1000, tmr.ALARM_AUTO, function(cb_timer)
if wifi.sta.getip() == nil then
print ("Waiting for IP address..")
else
cb_timer:unregister()
print ("WiFi mode: ", wifi.getmode ())
print ("MAC address: ", wifi.ap.getmac ())
print("Chip ID: ", node.chipid())
print("Heap Size: ", node.heap(), '\n')
print ("IP address: ", wifi.sta.getip ())
print ("Configuration done")
run()
end
end)
end
print("You have 3 seconds to abort\nWaiting...")
tmr.create():alarm(3000, tmr.ALARM_SINGLE, connect)
wifi.eventmon.register(wifi.eventmon.STA_CONNECTED, function(T)
print("\n\tSTA - CONNECTED" .. "\n\tSSID: "..T.SSID.."\n\tBSSID: " ..
T.BSSID.."\n\tChannel: "..T.channel)
end)
wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED, function(T)
print("\n\tSTA - DISCONNECTED" .. "\n\tSSID: "..T.SSID.."\n\tBSSID: " ..
T.BSSID.."\n\treason: "..T.reason)
end)
wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, function(T)
print("\n\tSTA - GOT IP" .. "\n\tStation IP: "..T.IP.."\n\tSubnet mask: " ..
T.netmask.."\n\tGateway IP: "..T.gateway)
end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment