Example: Serial port communication in LM2

Include library before calling serial functions
Source code    
  1. require('serial')

 

Opens given port, returns: port handle, or, in case of error, nil plus error message
Source code    
  1. port, err = serial.open(device, params)

Parameters:

  • device port device name, required
  • params parameters table, optional, (defaults are in bold):
    • baudrate 300, 600, 1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200, 230400
    • parity “none”, “even”, “odd”
    • databits 5, 6, 7, 8
    • stopbits 1, 2
    • duplex “full”, “half” (Note: “half” is required for RS-485)

 

Reads the specified number of bytes, execution is blocked until read is complete
Source code    
  1. res, err = port:read(bytes)

Parameters:

  • bytes number of bytes to read

 

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
Source code    
  1. res, err = port:read(bytes, timeout)

Parameters:

  • bytes number of bytes to read
  • timeout maximum time to wait for read to complete, minimum value and timer resolution is 0.1 seconds

 

Flushes any read/unsent bytes
Source code    
  1. port:flush()

 

Closes serial port, no other port functions may be called afterwards
Source code    
  1. port:close()

 

Example (resident scripts, RS-485 echo test)
Source code    
  1. -- open port on first call
  2. if not port then
  3. require('serial')
  4. port = serial.open('/dev/ttyS2', { baudrate = 9600, parity = 'even', duplex = 'half' })
  5. port:flush()
  6. end
  7.  
  8. -- port ready
  9. if port then
  10. -- read one byte
  11. char = port:read(1, 1)
  12. -- send back if read succeeded
  13. if char then
  14. port:write(char)
  15. end
  16. end