https://nodemcu.readthedocs.io/en/master/modules/uart/
串口發送數據
發送一個16進制到串口
uart.write(0, 0xaa)
注:
之所以有后面的這兩個是因為咱打印的時候其實單片機還沒有完全運行完內部的程序
3E 代表 > 20是空
咱加個定時器,每隔1S打印
打印字符串
local mytimer1 = tmr.create() function TimeFunction1() uart.write(0, "hello 8266") end mytimer1:register(1000, 1, TimeFunction1) mytimer1:start()
串口接收數據
接收到數據就把數據傳入回調函數(常用)
uart.on("data", 0,
function(dddd)
uart.write(0,dddd)
end
, 0)
"data" :代表注冊的串口數據接收回調函數
0: 只要接收到數據就傳給后面的回調函數的形參
function(dddd) 回調函數,數據傳給了 dddd
XXXXXX
對串口接收的數據dddd做處理
end
0: 數據不進行LUA指令解析
所有的數據都是靠串口
下面這些指令也不例外
典型處理形式
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)
參見: https://www.cnblogs.com/yangfengwu/p/11669373.html 學的是思想,而非程序本身
測試
以后直接在這里處理數據
提醒
按照上面的寫法以后,便不能下載程序,所有的指令也不能運行
這樣可以防止別人點擊 Reload 加載出來里面的程序
用戶需要重新刷空固件
然后再刷LUA開發的固件
然后再進行開發
https://www.cnblogs.com/yangfengwu/p/11949226.html 參考這一節重新刷固件
咱調試編程的時候為避免這種情況發生
建議的方式:
處理串口的數據另外用一個文件處理
init 延時加載那個文件
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的時間去操作清除文件
然后再進行下載調試