Serial Communication 3.1.11

The control box has serial communication. See User Manual for interface details.

WARNING

Due to communication instability and other reasons, errors may occur. In most cases, you need to use error handling mechanism to catch errors and prevent abnormal exit.

Open Serial Device

Opens a serial device, using baud rate 115200, 8 data bits, 1 stop bit, no parity by default.

  • Function: open from the [serial] module under lua module
  • Parameters:
    1. path: [str] Serial device address
  • Returns: [Serial] Serial instance, or throws error

Example

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

Set Timeout

Sets serial port timeout.

  • Function: set_timeout method under [Serial]
  • Parameters:
    1. timeout: [int] Timeout in milliseconds (ms). Optional, default 800ms
  • Returns: none

Example

com1:set_timeout(200)

Set Baud Rate

Sets serial port baud rate.

  • Function: set_baud_rate method under [Serial]
  • Parameters:
    1. baud_rate: [int] Serial port baud rate. Optional, default 115200
  • Returns: none, or throws connection error

Example

com1:set_baud_rate(9600)

Set Parity

Sets parity bit.

  • Function: set_parity method under [Serial]
  • Parameters:
    1. parity: [str] Parity bit (None: no parity; Odd: odd parity; Even: even parity). Optional, default no parity
  • Returns: none, or throws connection error

Example

com1:set_parity("Even")

Send Data

Sends u8 array via serial port.

  • Function: write method under [Serial]
  • Parameters:
    1. data: [list[int]] u8 array to send
  • Returns: none, or throws connection error

Example

com1:write({string.byte("123", 1, 3)}) -- Send string
com1:write({0x01, 0x02, 0x03}) -- Send HEX

Receive Data

Receives u8 array via serial port.

  • Function: read method under [Serial]
  • Parameters:
    1. len: [int] Maximum buffer length for single receive. Optional, default 64 bytes
  • Returns: [list[int]] Received u8 array, or throws connection error

Example

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)}) -- Send string
com1:write({0x01, 0x02, 0x03}) -- Send HEX

-- Read serial port, use pcall to catch errors
success, result = pcall(function() return com1:read() end)
if success then
  print(result) -- Print HEX
  print(string.char(table.unpack(result))) -- Print string
else
  print("Error: ", result)
end

-- Read serial port, errors not caught, will cause abnormal task exit on error
local data = com1:read()
print(data) -- Print HEX
print(string.char(table.unpack(data))) -- Print string