本帖最后由 沙漠之痕 于 2018-11-7 12:49 编辑
1. 模块开放热点,创建TCP服务器 Init.lua文件: tmr.alarm(0,5000,0,function() dofile("tcpserver.lua") end) init.lua文件结束 Tcpserver.lua文件 wifi.setmode(wifi.STATIONAP) local apcfg = { ssid="ESP8266-server", pwd="11223344" } wifi.ap.config(apcfg) 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 ) tcpserver.lua文件结束 2. 模块开放热点,创建服务器,客户端发送”open”打开继电器; 发送”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 apcfg = { ssid="ESP-server", pwd="11223344" } wifi.ap.config(apcfg) 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 ServerReceCnt = 0 ServerReceStat = true end) ClientSocket:on("disconnection",function() ClientSocket=nil print("\r\nDisconnec\r\n") 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) tcpserver.lua文件结束 与连接路由器相比,个人感觉这种方法比较笨拙,要是可以连接路由器, 若可以连接路由器既可以上网也可以控制继电器, 谁会连接模块热点不能上网去控制, 这里只是简单介绍如何使用。
|