​​https://nodemcu.readthedocs.io/en/master/modules/uart/​


串口发送数据

  ESP8266 LUA脚本语言开发: 外设篇-串口_串口




发送一个16进制到串口

  uart.write(0, 0xaa)  

ESP8266 LUA脚本语言开发: 外设篇-串口_串口_02





 ESP8266 LUA脚本语言开发: 外设篇-串口_回调函数_03




注:

ESP8266 LUA脚本语言开发: 外设篇-串口_回调函数_04



 之所以有后面的这两个是因为咱打印的时候其实单片机还没有完全运行完内部的程序

3E 代表 >      20是空


咱加个定时器,每隔1S打印

ESP8266 LUA脚本语言开发: 外设篇-串口_固件_05




ESP8266 LUA脚本语言开发: 外设篇-串口_回调函数_06





打印字符串


local mytimer1 = tmr.create() 

function TimeFunction1()
uart.write(0, "hello 8266")
end

mytimer1:register(1000, 1, TimeFunction1)

mytimer1:start()




ESP8266 LUA脚本语言开发: 外设篇-串口_数据_07




串口接收数据

  ESP8266 LUA脚本语言开发: 外设篇-串口_数据_08




  ESP8266 LUA脚本语言开发: 外设篇-串口_串口_09




接收到数据就把数据传入回调函数(常用)

uart.on("data", 0,

  function(dddd)

    uart.write(0,dddd)

  end

, 0)


"data" :代表注册的串口数据接收回调函数

0:         只要接收到数据就传给后面的回调函数的形参


function(dddd)  回调函数,数据传给了 dddd

 XXXXXX

   对串口接收的数据dddd做处理

end


0: 数据不进行LUA指令解析

    所有的数据都是靠串口

  下面这些指令也不例外

 ESP8266 LUA脚本语言开发: 外设篇-串口_数据_10





典型处理形式




 ESP8266 LUA脚本语言开发: 外设篇-串口_串口_11






local UsartReceiveData="";
local UsartReceiveDataCopy="";
local UsartReceiveFlage=false;
local UsartIdleCnt = 0;


local TimerMs = tmr.create()

TimerMs:register(1,1,function()

if UsartReceiveFlage == true then
UsartIdleCnt = UsartIdleCnt +1;
if UsartIdleCnt > 10 then
UsartIdleCnt = 0;
UsartReceiveFlage = false
UsartReceiveDataCopy = UsartReceiveData;
UsartReceiveData = "";
end
end

if UsartReceiveDataCopy ~= nil then
uart.write(0,UsartReceiveDataCopy)
UsartReceiveDataCopy = nil
end
end)
TimerMs:start()



uart.setup(0, 115200, 8, uart.PARITY_NONE, uart.STOPBITS_1)
uart.on("data",0,function(data)
UsartReceiveData = UsartReceiveData..data;
UsartReceiveFlage = true;
UsartIdleCnt = 0;
end, 0)




 学的是思想,而非程序本身


测试

ESP8266 LUA脚本语言开发: 外设篇-串口_串口_12






以后直接在这里处理数据



ESP8266 LUA脚本语言开发: 外设篇-串口_固件_13






提醒

  按照上面的写法以后,便不能下载程序,所有的指令也不能运行

  ESP8266 LUA脚本语言开发: 外设篇-串口_数据_14





  这样可以防止别人点击  Reload 加载出来里面的程序


  用户需要重新刷空固件

  然后再刷LUA开发的固件

  然后再进行开发

参考这一节重新刷固件


咱调试编程的时候为避免这种情况发生

建议的方式:

  处理串口的数据另外用一个文件处理

  ESP8266 LUA脚本语言开发: 外设篇-串口_lua_15







  init 延时加载那个文件


  ESP8266 LUA脚本语言开发: 外设篇-串口_数据_16









local T = tmr.create()
T:register(3000, 0, function()
if file.open("uart.lua", "r") then
file.close();
dofile("uart.lua")
end
end)
T:start();







这样,每次复位模块的时候,都有3S的时间去操作清除文件

ESP8266 LUA脚本语言开发: 外设篇-串口_lua_17








 然后再进行下载调试