ESP8266灯控硬件:使用淘宝ESP-01模块,带一个ESP8266插槽和一个5V继电器,220V转5V用拆下的手机充电器
ESP8266代码,开放TCP Server(80)端口,同时作为TCP Client连接远端TCP Server,可读取和配置pin1、pin2,可读取adc
WIFI_NAME = "MERCURY_204"
WIFI_PASSWORD = "Password"
SERVER_IP = "192.168.1.200"
SERVER_PORT = 8081
led1 = 3
led2 = 4
gpio.mode(led1, gpio.OUTPUT)
gpio.mode(led2, gpio.OUTPUT)
wifi.setmode(wifi.STATION)
wifi.sta.config(WIFI_NAME, WIFI_PASSWORD)
wifi.sta.connect()
wifi.sta.autoconnect(1)
Watchdog = 0
local function receiveData(data)
Watchdog = 0
local _GET = {}
for k, v in string.gmatch(data, "(%w+)=(%d*)") do
_GET[k] = v
end
local buf = "ID="..node.chipid();
if(_GET.PIN1 == "1")then
gpio.write(led1, gpio.HIGH);
print("led1 on")
elseif(_GET.PIN1 == "0")then
gpio.write(led1, gpio.LOW);
print("led1 off")
end
if(_GET.PIN1 ~= nil)then
buf = buf.." PIN1="..gpio.read(led1)
end
if(_GET.PIN2 == "1")then
gpio.write(led2, gpio.HIGH);
print("led2 on")
elseif(_GET.PIN2 == "0")then
gpio.write(led2, gpio.LOW);
print("led2 off")
end
if(_GET.PIN2 ~= nil)then
buf = buf.." PIN2="..gpio.read(led2)
end
if(_GET.ADC ~= nil)then
buf = buf.." ADC="..adc.read(0)
end
return buf
end
ClientConnectedFlag = 0
i=0
tmr.alarm(1, 1000, 1, function()
if wifi.sta.getip()== nil then
print("IP unavaiable, Waiting...")
i=i+1
if(i>10) then
print("restart nodeMCU")
node.restart()
end
elseif ClientConnectedFlag == 0 then
print("Connecting to Server...")
Client = net.createConnection(net.TCP, 0)
Client:connect(SERVER_PORT, SERVER_IP)
Client:on("receive", function(Client, data)
Client:send(receiveData(data));
collectgarbage();
end)
Client:on("connection", function(sck, c)
ClientConnectedFlag = 1
end)
Client:on("disconnection", function(sck, c)
ClientConnectedFlag = 0
end)
elseif Watchdog >= 120 then
Watchdog = 0
ClientConnectedFlag = 0
Client:close();
else
Watchdog = Watchdog + 1
end
end)
srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
conn:on("receive", function(client,data)
client:send(receiveData(data));
client:clo