串口通信 3.1.11
控制箱带有串口通信,接口对应关系详见用户手册。
机箱上对应 485 串口是 /dev/ttyS1,232 串口是 /dev/ttyS3,TTL 串口是 /dev/ttyS2。
设置超时时间
- 函数名:[Robot]下的方法
set_serial_timeout - 参数:
- device: [str] 串口设备地址
- timeout: [int] 超时时间,单位毫秒(ms)。默认800ms
- 返回:无
示例程序
lebai:set_serial_timeout("/dev/ttyS1", 100)
lebai.set_serial_timeout("/dev/ttyS1", 100)
设置波特率
- 函数名:[Robot]下的方法
set_serial_baud_rate - 参数:
- device: [str] 串口设备地址
- baud_rate: [int] 串口波特率。默认115200
- 返回:无
返回空 或 抛出连接错误
示例程序
lebai:set_serial_baud_rate("/dev/ttyS1", 9600)
lebai.set_serial_baud_rate("/dev/ttyS1", 9600)
设置奇偶校验位
- 函数名:[Robot]下的方法
set_serial_parity - 参数:
- device: [str] 串口设备地址
- parity: [Parity] 奇偶校验位(
None: 无奇偶校验;Odd: 奇校验;Even: 偶校验)。可选,默认无奇偶校验位
- 返回:无
返回空 或 抛出连接错误
示例程序
lebai:set_serial_parity("/dev/ttyS1", "None")
lebai.set_serial_parity("/dev/ttyS1", "None")
发送数据
通过串口发送u8数组。
- 函数名:[Robot]下的方法
write_serial - 参数:
- device: [str] 串口设备地址
- data: [list[int]] 待发送的u8数组
- 返回:无
返回空 或 抛出连接错误
示例程序
lebai:write_serial("/dev/ttyS1", {0x31, 0x32, 0x33})
lebai.write_serial("/dev/ttyS1", [0x31, 0x32, 0x33])
接收数据
通过串口接收u8数组。
- 函数名:[Robot]下的方法
read_serial - 参数:
- device: [str] 串口设备地址
- len: [int] 单次接收的最大缓冲长度。可选,默认64字节
- 返回: [list[int]] 接收到的u8数组
返回u8数组 或 抛出连接错误
示例程序
data = lebai:read_serial("/dev/ttyS1", 3)
print(data)
data = lebai.read_serial("/dev/ttyS1", 3)
print(data)
清除缓冲区
清除串口收发缓存的数据。
- 函数名:[Robot]下的方法
clear_serial - 参数:
- device: [str] 串口设备地址
- 返回:无
返回空 或 抛出连接错误
示例程序
lebai:clear_serial("/dev/ttyS1")
lebai.clear_serial("/dev/ttyS1")
示例
local path = "/dev/ttyS1"
lebai:set_serial_baud_rate(path, 9600)
local str = "123"
lebai:write_serial(path, {string.byte(str, 1, #str)}) -- 发送字符串
lebai:write_serial(path, {0x01, 0x02, 0x03}) -- 发送HEX
local data = lebai:read_serial(path)
print(data) -- 打印HEX
print(string.char(table.unpack(data))) -- 打印字符串
path = "/dev/ttyS1"
lebai.set_serial_baud_rate(path, 9600)
str = "123"
lebai.write_serial(path, [ord(char) for char in str]) # 发送字符串
lebai.write_serial(path, [0x01, 0x02, 0x03]) # 发送HEX
data = lebai.read_serial(path)
print(data) # 打印HEX
print(''.join(chr(b) for b in data)) # 打印字符串
