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:close();
collectgarbage();
end)
end)
PC上使用QT開放兩個TCP Server(8080、8081),8081端口用於管理設備,8080端口用於與Android終端通訊
打印Log
Android終端作爲TCP Client連接到PC的TCP 8080端口,通過Server獲取和配置已連接的設備信息
設備、PC、Android連接方式:
方案改進:利用了之前買的nanopi開發版,手掌心大小,通過網線接入到局域網中,配置靜態ip爲192.168.1.200,將nanopi代替pc
nanopi上跑Ubuntu-Core with Qt-Embedded系統,在pc上建立ubuntux64虛擬機,安裝好arm交叉編譯器,在pc上完成程序移植,因爲下載qt太慢,直接用c重新寫了一遍,相比之下c代碼對字符串的處理真是麻煩,全部當數組操作。調試ok後編譯拷貝到nanopi上,賦予可執行權限,就可以通過nanopi控制esp8266了