串口通信 3.1.11

控制箱带有串口通信,接口对应关系详见用户手册

注意

由于通信不稳定等原因,可能导致错误发生。大多数情况下,需要使用错误处理机制来捕获错误,防止异常退出。

打开串口设备

打开串口设备,默认使用波特率115200、8 位数据位、1 位停止位、无检验位。

  • 函数名:lua模块下[serial]模块的函数open
  • 参数:
    1. path: [str] 串口设备地址
  • 返回:[Serial] 串口实例,或抛出错误

示例程序

local com1 = serial.open("/dev/ttyS1")

设置超时时间

设置串口超时时间。

  • 函数名:[Serial]下的方法set_timeout
  • 参数:
    1. timeout: [int] 超时时间,单位毫秒(ms)。可选,默认800ms
  • 返回:无

示例程序

com1:set_timeout(200)

设置波特率

设置串口波特率。

  • 函数名:[Serial]下的方法set_baud_rate
  • 参数:
    1. baud_rate: [int] 串口波特率。可选,默认115200
  • 返回:无,或抛出连接错误

示例程序

com1:set_baud_rate(9600)

设置奇偶校验位

设置奇偶校验位。

  • 函数名:[Serial]下的方法set_parity
  • 参数:
    1. parity: [str] 奇偶校验位(None: 无奇偶校验; Odd: 奇校验; Even: 偶校验)。可选,默认无奇偶校验位
  • 返回:无,或抛出连接错误

示例程序

com1:set_parity("Even")

发送数据

通过串口发送u8数组。

  • 函数名:[Serial]下的方法write
  • 参数:
    1. data: [list[int]] 待发送的u8数组
  • 返回:无,或抛出连接错误

示例程序

com1:write({string.byte("123", 1, 3)}) -- 发送字符串
com1:write({0x01, 0x02, 0x03}) -- 发送HEX

接收数据

通过串口接收u8数组。

  • 函数名:[Serial]下的方法read
  • 参数:
    1. len: [int] 单次接收的最大缓冲长度。可选,默认64字节
  • 返回:[list[int]] 接收到的u8数组,或抛出连接错误

示例程序

local com1 = serial.open("/dev/ttyS1")
com1:set_timeout(200)
com1:set_baud_rate(9600)

local str = "123"
com1:write({string.byte(str, 1, #str)}) -- 发送字符串
com1:write({0x01, 0x02, 0x03}) -- 发送HEX

-- 读取串口,使用pcall捕获错误
success, result = pcall(function() return com1:read() end)
if success then
  print(result) -- 打印HEX
  print(string.char(table.unpack(result))) -- 打印字符串
else
  print("Error: ", result)
end

-- 读取串口,由于未捕获错误,当发生错误时,任务异常退出
local data = com1:read()
print(data) -- 打印HEX
print(string.char(table.unpack(data))) -- 打印字符串