ESP8266-01S基于lua的最简串口wifi透传源码

ESP8266-01S基于lua的最简串口wifi透传源码


修改记录:
2020年5月31日创建

源码

完整UART WIFI透传程序
从网上照抄,做了一点点修改,模块设置成AP模式,ssid为Hellow8266,程序下载后运行。查询手机的无线和网络,其中的WLAN,可以找到名为Hellow8266的连接点。

–[[
module ESP8266-07S LED_Pin = GPIO14 = 5
GPIO5=1NC
GPIO4=2 NC
GPIO2=3 for Direct
GPIO2=4 for Throttle

ESP8266-01S LED_Pin = 4 Here used for channel 2 (Dirrect) output
GPIO2=3 for Direct
GPIO2=4 for Throttle
20200706 recoded
]]
–defined client connected socket

lighton = 0
count = 0
Ledpin = 4
gpio.mode(Ledpin,gpio.OUTPUT)
gpio.mode(Ledpin,gpio.HIGH)

tmr.alarm(0, 1000, 1, function()
gpio.write(Ledpin,1-gpio.read(Ledpin))
end)
–tmr.stop(0)
uartsocket = nil
buf=""
uart.setup(0,115200,8,0,1,0)
SendCount = 0
UartCounter = 0

wifi.setmode(wifi.SOFTAP)
cfg={
ssid=“Hellow8266”,
pwd=“11223344”,
auth=wifi.WPA2_PSK,
ip=“192.168.1.5”,
netmask=“255.255.255.0”,
gateway=“192.168.1.1”
}
wifi.ap.setip(cfg)
wifi.ap.config(cfg)
print("\r")
print(“My Ap ip:”…wifi.ap.getip())
print(“My Ap mac:”…wifi.ap.getmac())
TCPSever = net.createServer(net.TCP,28800)

TCPSever:listen(8080,function(socket)
socket:on(“receive”,function(socket,data)
uartsocket = socket
if data == “q” then
–gpio.write(ledpin,gpio.HIGH)
restring = string.format("%03d %s OFF\r\n",SendCount,data)
socket:send(restring)
elseif data == “a” then
–gpio.write(ledpin,gpio.LOW)
restring = string.format("%03d %s ON\r\n",SendCount,data)
socket:send(restring)
else
restring = string.format(“Client:%03d %s\r\n”,string.len(data),data)
socket:send(restring)
uart.write(0,restring)
end
SendCount = SendCount + 1
–reset the counter of send
if SendCount > 255 then
SendCount = 1
end
end)
socket:on(“disconnection”,function(sck,c)
socket = nil
end)

end)

uart.on(“data”, “\r”, function(Rec)
–uart.write(0, Rec)
UartCounter = UartCounter+1
if UartCounter > 99 then
UartCounter =0
end
buf = string.format(“UART:%02d%03d%s\r\n”,
UartCounter,string.len(Rec),Rec)
–uart.write(0, buf)
if uartsocket ~= nil then
uartsocket:send(buf)
else
uart.write(0, “Client disconneected…\r\n”)
end
end, 0)

源码说明

1、tmr.alarm(0, 1000, 1, function()这段程序使得ESP8266-01S模块上的LED以每秒1次的频率闪烁,表示程序正常运行;
2、wifi.setmode(wifi.SOFTAP)及以下这段程序,配置wifi
3、TCPSever:listen(8080,function(socket) 及以下这段程序,等待手机APP或是电脑以Clinet模式链接到ESP8266-01S;其中,手机端发“q“使ESP8266-01S模块上的LED灭;手机端发“a“使ESP8266-01S模块上的LED亮;测试通讯用的,如不用,则
socket:send(restring)
把收到的数据,简单处理一下返回给链接的客户段(如手机APP);
uart.write(0,restring)
把收到的数据,简单处理一下,ESP8266-01S模块的串口TXD送出。
4、 uart.on(“data”, “\r”, function(Rec)及以下代码,从ESP8266-01S模块的串口RXD接收数据,通过uartsocket:send(buf)送出;
5、注意,wifi通讯信息字符串的形式传送,并以回车符作结束,信息app或单片机程序发送字符串必须加回车符”\r"结尾,否则,会不成功,或其他错误。

操作界面之一

在这里插入图片描述
ESPlorer串口上到数据

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值