Air202入坑指南4---UART2(简单使用)

Air202入坑指南4—UART2

下面的代码就是这个串口的简单使用的代码,可见波特率是115200,8N1.其他就是定义了一个信号量UART2_RECEIVE,这个信号量作为接收到信号之后串口怎么处理的标志使用注册串口事件的处理函数uart.on。同时下面又实现了两个函数,分别是读取和接收。

--- 模块功能:串口功能测试(TASK版)
-- @author openLuat
-- @module uart.testUartTask
-- @license MIT
-- @copyright openLuat
-- @release 2018.10.20
require "utils"
require "pm"
module(..., package.seeall)

-- 配置串口2  
pm.wake("mcuUart.lua")
uart.setup(2, 115200, 8, uart.PAR_NONE, uart.STOP_1)
uart.on(
    2,
    "receive",
    function()
        sys.publish("UART2_RECEIVE")
    end
)

-- 串口读指令
local function read(uid, timeout)
    local cache_data = ""
    if timeout == 0 or timeout == nil then
        timeout = 20
    end
    sys.wait(timeout)
    while true do
        local s = uart.read(uid, "*l")
        if s == "" then
            return cache_data
        else
            cache_data = cache_data .. s
        end
    end
end
function write(uid, s)
    log.info("testUart.write", s)
    uart.write(uid, s)
end
-- 串口收到什么就返回什么
sys.taskInit(
    function()
        while true do
            if sys.waitUntil("UART2_RECEIVE", 1000) then
                local dat = read(2, 20)
                log.info(" 串口收到的数据:", dat)
                write(2, dat)
            else
                --write(2, "read wait timeout!")
                log.info(" 串口没有收到数据: ")
            end
        end
    end
)


结果

结果如上图显示

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值