Serial Communication 3.1.11

The control box has serial communication. For the interface mapping, see the User Manual.

The 485 serial port on the chassis corresponds to /dev/ttyS1, the 232 serial port to /dev/ttyS3, and the TTL serial port to /dev/ttyS2.

Set Timeout

  • Function name: Method set_serial_timeout under [Robot]
  • Parameters:
    1. device: [str] Serial device address
    2. timeout: [int] Timeout duration in milliseconds (ms). Default 800ms
  • Return: None

Example Program

lebai:set_serial_timeout("/dev/ttyS1", 100)

Set Baud Rate

  • Function name: Method set_serial_baud_rate under [Robot]
  • Parameters:
    1. device: [str] Serial device address
    2. baud_rate: [int] Serial baud rate. Default 115200
  • Return: None

Returns empty or throws a connection error

Example Program

lebai:set_serial_baud_rate("/dev/ttyS1", 9600)

Set Parity Bit

  • Function name: Method set_serial_parity under [Robot]
  • Parameters:
    1. device: [str] Serial device address
    2. parity: [Parity] Parity bit (None: no parity; Odd: odd parity; Even: even parity). Optional, default no parity
  • Return: None

Returns empty or throws a connection error

Example Program

lebai:set_serial_parity("/dev/ttyS1", "None")

Send Data

Send a u8 array through the serial port.

  • Function name: Method write_serial under [Robot]
  • Parameters:
    1. device: [str] Serial device address
    2. data: [list[int]] u8 array to send
  • Return: None

Returns empty or throws a connection error

Example Program

lebai:write_serial("/dev/ttyS1", {0x31, 0x32, 0x33})

Receive Data

Receive a u8 array through the serial port.

  • Function name: Method read_serial under [Robot]
  • Parameters:
    1. device: [str] Serial device address
    2. len: [int] Maximum buffer length for a single receive. Optional, default 64 bytes
  • Return: [list[int]] Received u8 array

Returns a u8 array or throws a connection error

Example Program

data = lebai:read_serial("/dev/ttyS1", 3)
print(data)

Clear Buffer

Clear the data cached in the serial port send/receive buffers.

  • Function name: Method clear_serial under [Robot]
  • Parameters:
    1. device: [str] Serial device address
  • Return: None

Returns empty or throws a connection error

Example Program

lebai:clear_serial("/dev/ttyS1")

Example

local path = "/dev/ttyS1"
lebai:set_serial_baud_rate(path, 9600)

local str = "123"
lebai:write_serial(path, {string.byte(str, 1, #str)}) -- send string
lebai:write_serial(path, {0x01, 0x02, 0x03}) -- send HEX
local data = lebai:read_serial(path)
print(data) -- print HEX
print(string.char(table.unpack(data))) -- print string