1. 程式人生 > >8-Air202串口學習(Air202串口1接收到什麽內容就回復什麽內容)

8-Air202串口學習(Air202串口1接收到什麽內容就回復什麽內容)

-- == 源碼 not () html file 打開 tco

實現的功能

技術分享圖片

技術分享圖片

技術分享圖片

有人會想,不就是個串口接收到什麽就會什麽的程序嘛!!!!!!!!!!!!!!有什麽好說的!!

實現此功能的程序是很多,但是,但是,但是.....我寫的程序更註重於開發和實用,不信往下看

先貼出來程序,,,

技術分享圖片 技術分享圖片
module(...,package.seeall)

local function print(...)
    _G.print(...)
end

print("dofile usart.lua................................................");

local UART_ID = 1 --uart1
local uartReadData = "";
local uartReadDataCopy = "";
local uartReadDataCnt = 0;
local uartReadDataCntCopy = 0;

--定時器空閑中斷檢測10ms
local function TimerFunc4()
       if  uartReadDataCnt ~= 0 then
        uartReadDataCnt = 0;
        uartReadDataCntCopy = 0;
        uartReadDataCopy = uartReadData;
        uartReadData = "";
        uart.write(UART_ID,uartReadDataCopy)
       else
            uartReadDataCntCopy = uartReadDataCnt;
       end
end
sys.timer_loop_start(TimerFunc4,10)


--讀取串口接收到的數據
local function read()
    local data = ""
    while true do
        data = uart.read(UART_ID,"*l",0)
        if not data or string.len(data) == 0 then break end
        uartReadData = uartReadData..data;
        uartReadDataCnt = uartReadDataCnt +1
    end
end

pm.wake("wake")
--註冊串口的數據接收函數,串口收到數據後,會以中斷方式,調用read接口讀取數據
sys.reguart(UART_ID,read)
--配置並且打開串口
uart.setup(UART_ID,115200,8,uart.PAR_NONE,uart.STOP_1)
技術分享圖片 技術分享圖片

凡是看懂我這篇文章的才能瞬間看懂我的這個程序

http://www.cnblogs.com/yangfengwu/p/8912072.html 是否看懂了,我沒有騙人吧!!凡是串口接收的程序,無論單片機還是上位機這個接收

程序的模式是通吃的......

所以下各個部分的功能

技術分享圖片

如果一開始調用的

pm.wake("aaaa")

假如想讓系統休眠----pm.sleep("aaaa")

技術分享圖片

技術分享圖片

不過程序上讓我產生了疑惑

技術分享圖片

後面的0是幹什麽的.....................

然後就看源碼

技術分享圖片

算啦說一下整體的思路

串口中斷裏面有一個負責接收數據的字符串變量,還有一個數據個數累加的變量

假設串口一次發100個數據,,然後間隔1S發一次

定時器是每間隔10Ms檢測一次

如果數據沒有接收完 uartReadDataCnt 會一直累加,因為每間隔10Ms去檢測一次,uartReadDataCnt在這期間會向上累加...

所以數據沒有接收完成的時候進入定時器的時候 uartReadDataCntCopy 總是 < uartReadDataCnt

假設接收完了,因為是1S發一次,而定時器是每隔10Ms檢測一次,所以會檢測到uartReadDataCntCopy == uartReadDataCnt

所以....處理數據就可以了,,,接收到一條完整的數據了....

技術分享圖片

8-Air202串口學習(Air202串口1接收到什麽內容就回復什麽內容)