Serial port communication in LM2
Example: Serial port communication in LM2
Include library before calling serial functions
- require('serial')
Opens given port, returns: port handle, or, in case of error, nil plus error message
- 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
- 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
- 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
- port:flush()
Closes serial port, no other port functions may be called afterwards
- port:close()
Example (resident scripts, RS-485 echo test)
- -- open port on first call
- if not port then
- require('serial')
- port = serial.open('/dev/ttyS2', { 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