Serial communication

Serial communication (RS-232 / RS-485) library #

Load the library:

require('serial')

Library functions #

open(device, params) #

Opens given port, returns port instance, or, in case of error, nil plus error message.

Parameters:

  • device port device name, (string, required)
  • params parameters table, (table, optional), (defaults are in bold):
    • baudrate (number) 115200
    • parity (string) 'none', 'even' or 'odd'
    • databits (number) 5, 6, 7 or 8
    • stopbits (number) 1 or 2
    • duplex (string) 'full' or 'half' ('half' is required for RS-485)

Instance functions #

read(bytes) #

Reads the specified number of bytes, execution is blocked until read is complete.

Parameters:

  • bytes number of bytes to read

write(str) #

Writes the specified string to the serial port. Returns number of bytes written, or, in case of error, nil plus error message.

Parameters:

  • str string to write

read(bytes, timeout) #

Reads until timeout occurs or the specified number of bytes is received, whichever happens first. Returns data plus number of bytes read, or, in case of error, nil plus error message.

Parameters:

  • bytes number of bytes to read; set to -1 to read all buffered data from the port
  • timeout maximum time to wait for read to complete, minimum value and timer resolution is 0.1 seconds; set to -1 to skip waiting and return bytes immediately if available

flush() #

Flushes any read/unsent bytes.


drain() #

Waits until all output has been transmitted.


close() #

Closes serial port, no other port functions may be called afterwards.


Example (resident script, RS-485 echo test):

-- open port on first call
if not port then
  require('serial')
  port = serial.open('/dev/RS485', {
    baudrate = 9600,
    parity = 'even',
    duplex = 'half'
  })
  port:flush()
end

-- port ready
if port then
  -- read one byte
  char = port:read(1, 1)
  -- send back if read succeeded
  if char then
    port:write(char)
  end
end