3.1.11
Serial CommunicationWARNING
Due to reasons such as unstable communication, errors may occur. In most cases, it is necessary to use the error handling mechanism to catch errors and prevent abnormal exits.
Open Serial Port Device
com = serial.open(path)
By default, it uses a baud rate of 115200, 8 data bits, 1 stop bit, and no parity. Please contact us if you need to change these settings.
- Parameters
path
: Serial port device address.
Returns a serial port instance or throws an error.
Set Timeout
com:set_timeout(timeout)
- Parameters
timeout
: Timeout in milliseconds (ms). Default is 800ms.
Set Baud Rate
com:set_baud_rate(baud_rate)
Set the serial port baud rate.
- Parameters
baud_rate
: Serial port baud rate. Default is 115200.
Returns nothing or throws a connection error.
Set Parity
com:set_parity(parity)
Set the parity bit.
- Parameters
parity
: Parity bit (None: no parity; Odd: odd parity; Even: even parity). Default is no parity.
Returns nothing or throws a connection error.
Send Data
com:write(data)
Send a u8 array via serial port.
- Parameters
data
: u8 array to be sent.
Returns nothing or throws a connection error.
Receive Data
data = com:read(len)
Receive a u8 array via serial port.
- Parameters
len
: Maximum buffer length for a single reception, can be empty, default is 64 bytes.
Returns a u8 array or throws a 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 from serial port, using 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 from serial port, since errors are not caught, the task will exit abnormally when an error occurs
local data = com1:read()
print(data) -- Print HEX
print(string.char(table.unpack(data))) -- Print string