本帖最后由 沙漠之痕 于 2018-11-7 12:48 編輯
1. 連接路由器,創(chuàng)建服務器監(jiān)聽8080端口 init.lua文件: tmr.alarm(0,5000,0,function() dofile("tcpserver.lua") end) init.lua文件結束 tcpserver.lua文件: wifi.setmode(wifi.STATIONAP) local stacfg = { ssid = "qqqqq", pwd = "11223344" } wifi.sta.config(stacfg) wifi.sta.autoconnect(1) local ClientSocket = nil Server = net.createServer(net.TCP,28800) Server:listen(8080,function(socket) ClientSocket=socket ClientSocket:on("receive",function(sck,data) uart.write(0,data) end) ClientSocket:on("disconnection",function() ClientSocket=nil print("Disconnec") end) end) printip = 0 wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED,function(T) printip = 0 end) wifi.eventmon.register(wifi.eventmon.STA_GOT_IP,function(T) if printip==0 then print("+IP: "..T.IP) end printip=1 end) tcpserver.lua文件結束 手機連接上路由器,并去連接模塊開啟的服務器,模塊ip即為服務器ip通過串口已經打印出 通過手機客戶端給模塊服務器發(fā)送數據通過模塊的串口輸出 2. 通過手機發(fā)送”open”打開繼電器;發(fā)送 “close”關閉繼電器 init.lua文件 RELAY_Pin = 1 gpio.mode(RELAY_Pin,gpio.OUTPUT) gpio.write(RELAY_Pin,0) tmr.alarm(0,5000,0,function() dofile("tcpserver.lua") end) init.lua文件結束 tcpserver.lua文件: ServerReceData = "" ServerReceCnt = 0 ServerReceStat = false wifi.setmode(wifi.STATIONAP) local stacfg = { ssid = "qqqqq", pwd = "11223344" } wifi.sta.config(stacfg) wifi.sta.autoconnect(1) local ClientSocket = nil Server = net.createServer(net.TCP,28800) Server:listen(8080,function(socket) ClientSocket=socket ClientSocket:on("receive",function(sck,data) ServerReceData = ServerReceData..data ServerReceStat = true ServerReceCnt = 0 end) ClientSocket:on("disconnection",function() ClientSocket=nil print("Disconnec") end) end ) tmr.alarm(1,10,1,function() if ServerReceStat == true then ServerReceCnt = ServerReceCnt + 1 if ServerReceCnt >= 10 then if ServerReceData == "open" then gpio.write(RELAY_Pin,1) end if ServerReceData == "close" then gpio.write(RELAY_Pin,0) end uart.write(0,ServerReceData) ServerReceData = "" ServerReceCnt = 0 ServerReceStat = false end end end) ---------------Got IP ------------------- printip = 0 wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED,function(T) printip = 0 end) wifi.eventmon.register(wifi.eventmon.STA_GOT_IP,function(T) if printip==0 then print("+IP: "..T.IP) end printip=1 end) -------------END Got IP ------------------ tcpserver.lua文件結束
手機連接路由器并連接服務器
交流QQ:1813763867 QQ群:607064330
|