LibSerialPort.jl – access serial ports

LibSerialPortModule

The LibSerialPort module provides access to serial ports (UARTs or USB/Bluetooth devices that emulate their operating-system interface) using the portable C library libserialport.

It defines the SerialPort type, which is returned by LibSerialPort.open. This is a subtype of Base.IO and can therefore be used like a file handle, using many of the same read, write, print, etc. methods defined for Base.IO.

Example

using LibSerialPort

list_ports()
ports = get_port_list()

sp = LibSerialPort.open("/dev/ttyUSB0", 115200)
set_flow_control(sp)
sp_flush(sp, SP_BUF_BOTH)
write(sp, "hello\n")
println(readline(sp))
close(sp)
source

Enumerating serial ports

LibSerialPort.list_portsFunction
list_ports([nports_guess::Integer])`

Print a list of currently visible ports, along with some basic info.

nports_guess provides the number of ports guessed. Its default is 64.

source
LibSerialPort.get_port_listFunction
get_port_list([nports_guess::Integer])

Return a vector of currently visible ports.

nports_guess provides the number of ports guessed. Its default is 64.

source
LibSerialPort.print_port_metadataFunction
print_port_metadata(sp::SerialPort; show_config::Bool = true)

Print info found for this port. Note: port should be open to obtain a valid FD/handle before accessing fields.

show_config is true by default and prints out the current port settings.

source

Opening and configuring ports

Base.openMethod
open(portname::AbstractString, baudrate::Integer;
     mode::SPMode, ndatabits::Integer,
     parity::SPParity, nstopbits::Integer)

Construct, configure and open a SerialPort object.

  • portname is the name of the serial port to open. Typical port names available depend on the operating system. Some valid names are listed by get_port_list(), but there are can be others and aliases:
    • Linux: "/dev/ttyS0", "/dev/ttyUSB0", "/dev/serial/by-id/..."
    • macOS: "/dev/cu.usbserial-0001", "/dev/cu.Bluetooth-Incoming-Port"
    • Windows: "COM1", "COM2","COM3"
  • baudrate is the data signalling rate, or the reciprocal duration of one data bit, in bits/s. The set of values supported depends on the UART hardware, but typically includes e.g. 9600, 19200 and 115200.
  • mode selects in which direction of transmission access is requested and can take the values: SP_MODE_READ, SP_MODE_WRITE, and SP_MODE_READ_WRITE (default).

The parameters ndatabits, parity and nstopbits have the same meaning as in set_frame and default to the common “8N1” frame format (8 data bits, no parity, one stop bit).

To set the flow-control method, use set_flow_control.

source
Base.openMethod
open(sp::SerialPort; mode::SPMode = SP_MODE_READ_WRITE)

Open the serial port sp.

mode selects in which direction of transmission access is requested and can take the values: SP_MODE_READ, SP_MODE_WRITE, and SP_MODE_READ_WRITE (default).

source
LibSerialPort.set_speedFunction
set_speed(sp::SerialPort, baudrate::Integer)

Set the data signalling rate, or the reciprocal duration of one data bit, in bits/s. The set of values supported depends on the UART hardware, but typically includes e.g. 9600, 19200 and 115200.

Raise an ErrorException if bps is not a value supported by the driver or hardware.

source
LibSerialPort.set_frameFunction
set_frame(sp::SerialPort;
          ndatabits::Integer = 8,
          parity::SPParity   = SP_PARITY_NONE,
          nstopbits::Integer = 1)

Configure the data framing parameters. Defaults to the very common “8N1” scheme, which consists of a start bit followed by eight data bits, no parity bit, one stop bit.

for more details.

  • ndatabits is the number of data bits, which is 8 in the common "8N1" scheme

  • parity controls the presence and value of a party bit and can take the values SP_PARITY_NONE (default), SP_PARITY_ODD, SP_PARITY_EVEN, SP_PARITY_MARK and SP_PARITY_SPACE

  • nstopbits sets the number of stop bits, typically 1 (default) or 2

source
LibSerialPort.set_flow_controlFunction
set_flow_control(sp::SerialPort;
                 rts::SPrts = SP_RTS_OFF,
                 cts::SPcts = SP_CTS_IGNORE,
                 dtr::SPdtr = SP_DTR_OFF,
                 dst::SPdsr = SP_DSR_IGNORE,
                 xonxoff::SPXonXoff = SP_XONXOFF_DISABLED)

Configure the flow-control lines and method. Many systems don't support all options. If an unsupported option is requested, the library will return SP_ERR_SUPP.

  • rts controls the output line Ready To Send (RTS) and can take the values SP_RTS_OFF (default), SP_RTS_ON and SP_RTS_FLOW_CONTROL.

  • cts controls the input line Clear To Send (CTS) and can take the values SP_CTS_IGNORE (default) and SP_CTS_FLOW_CONTROL

  • dtr controls the output line Data Terminal Ready (DTR) and can take the values SP_DTR_OFF (default), SP_DTR_ON, and SP_DTR_FLOW_CONTROL

  • dsr controls the input line Data Set Ready (DSR) and can take the values SP_DSR_IGNORE (default) and SP_DSR_FLOW_CONTROL

  • xonxoff controls whether software flow control via the control bytes XOFF (pause transmission, 0x13, Ctrl-S) and XON (resume transmission, 0x11, Ctrl-Q) is active, and in which direction; it can take the values: SP_XONXOFF_DISABLED (default), SP_XONXOFF_IN, SP_XONXOFF_OUT, and SP_XONXOFF_INOUT

source
Base.isopenMethod
isopen(sp::SerialPort) -> Bool

Determine whether a SerialPort object is open.

source
Base.eofMethod
eof(sp::SerialPort) -> Bool

Return the “end-of-file” state (true or false). Since serial ports do not have any standard mechanism for signalling the end of a transmitted file, this is just a dummy function that returns whatever Boolean value eof was previously set with seteof(sp, eof). Returns false by default.

source
LibSerialPort.set_read_timeoutFunction
set_read_timeout(sp::SerialPort, seconds::Real)

Set a read timeout limit of t > 0 seconds for the total (cumulative) time that subsequently called blocking read functions can wait before a Timeout exception is thrown.

Example

sp=LibSerialPort.open("/dev/ttyUSB0", 115200)
# wait until either two lines have been received
# or 10 seconds have elapsed
set_read_timeout(sp, 10)
try
    line1 = readuntil(sp, '\n')
    line2 = readuntil(sp, '\n')
catch e
    if isa(e, LibSerialPort.Timeout)
        println("Too late!")
    else
        rethrow()
    end
end
clear_read_timeout(sp)

See also: clear_read_timeout, set_write_timeout

source
LibSerialPort.set_write_timeoutFunction
set_write_timeout(sp::SerialPort, seconds::Real)

Set a write timeout limit of t > 0 seconds for the total (cumulative) time that subsequently called blocking read functions can wait before a Timeout exception is thrown.

Example

sp=LibSerialPort.open("/dev/ttyUSB0", 300)
# wait until either 4000 periods have been
# passed on to the serial-port driver or
# 10 seconds have elapsed
set_write_timeout(sp, 10)
try
    for i=1:50 ; write(sp, '.' ^ 80); end
catch e
    if isa(e, LibSerialPort.Timeout)
        println("This took too long!")
    else
        rethrow()
    end
end
clear_write_timeout(sp)

See also: clear_write_timeout, set_read_timeout

source
LibSerialPort.clear_read_timeoutFunction
clear_read_timeout(sp::SerialPort)

Cancel any previous read timeout, such that blocking read operations will now wait without any time limit.

source
LibSerialPort.Lib.sp_flushFunction
sp_flush(port::Port, buffers::SPBuffer)
sp_flush(port::SerialPort, buffers::SPBuffer)

Discard data in the selected serial-port buffer(s).

Supported values for buffers: SP_BUF_INPUT, SP_BUF_OUTPUT, SP_BUF_BOTH

Returns SP_OK upon success or raises an ErrorException otherwise.

Note

Not to be confused with Base.flush, which writes out buffered data rather than discarding it: the underlying libserialport C library unfortunately uses the verb “flush” differently from its normal meaning for Base.IO (sp_drain provides the latter in this library).

source

Read and write methods from Base

Many of the read/write methods defined in Base that operate on an object of type IO can also be used with objects of type SerialPort. Therefore, also consult the documentation for

Base.read(::IO, ::Any)
Base.read!
Base.readbytes!
Base.readchomp
Base.readavailable
Base.readline
Base.readlines
Base.eachline
Base.write
Base.print(::IO, ::Any)

Additional read methods

Base.readMethod
read(sp::SerialPort)

Return all incoming bytes currently available in the UART as a Vector{UInt8}.

Note

Julia's Base module defines read(s::IO, nb::Integer = typemax(Int)). This method overrides the default value nb to bytesavailable(sp), which is useful for this context.

source
LibSerialPort.nonblocking_readMethod
nonblocking_read(sp::SerialPort)

Read everything from the specified serial ports sp input buffer, one byte at a time, until it is empty. Returns a String.

source