LibSerialPort.jl – access serial ports
LibSerialPort
— ModuleThe 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)
Enumerating serial ports
LibSerialPort.list_ports
— Functionlist_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
.
LibSerialPort.get_port_list
— Functionget_port_list([nports_guess::Integer])
Return a vector of currently visible ports.
nports_guess
provides the number of ports guessed. Its default is 64
.
LibSerialPort.print_port_metadata
— Functionprint_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.
Opening and configuring ports
Base.open
— Methodopen(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 byget_port_list()
, but there are can be others and aliases:- Linux:
"/dev/ttyS0"
,"/dev/ttyUSB0"
,"/dev/serial/by-id/..."
- Linux:
- macOS:
"/dev/cu.usbserial-0001"
,"/dev/cu.Bluetooth-Incoming-Port"
- macOS:
- Windows:
"COM1"
,"COM2"
,"COM3"
- Windows:
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
, andSP_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
.
LibSerialPort.SerialPort
— MethodSerialPort(portname::AbstractString)
Constructs and returns a SerialPort
object.
Base.open
— Methodopen(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).
Base.close
— Methodclose(sp::SerialPort)
Close the serial port sp
.
LibSerialPort.set_speed
— Functionset_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.
LibSerialPort.set_frame
— Functionset_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 is8
in the common "8N1" schemeparity
controls the presence and value of a party bit and can take the valuesSP_PARITY_NONE
(default),SP_PARITY_ODD
,SP_PARITY_EVEN
,SP_PARITY_MARK
andSP_PARITY_SPACE
nstopbits
sets the number of stop bits, typically1
(default) or2
LibSerialPort.set_flow_control
— Functionset_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 valuesSP_RTS_OFF
(default),SP_RTS_ON
andSP_RTS_FLOW_CONTROL
.cts
controls the input line Clear To Send (CTS) and can take the valuesSP_CTS_IGNORE
(default) andSP_CTS_FLOW_CONTROL
dtr
controls the output line Data Terminal Ready (DTR) and can take the valuesSP_DTR_OFF
(default),SP_DTR_ON
, andSP_DTR_FLOW_CONTROL
dsr
controls the input line Data Set Ready (DSR) and can take the valuesSP_DSR_IGNORE
(default) andSP_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
, andSP_XONXOFF_INOUT
Base.isopen
— Methodisopen(sp::SerialPort) -> Bool
Determine whether a SerialPort
object is open.
Base.eof
— Methodeof(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.
LibSerialPort.seteof
— Functionseteof(sp::SerialPort, state::Bool)
Set the return value of eof(sp)
to state
.
LibSerialPort.get_port_settings
— Functionget_port_settings(sp::SerialPort)
Return port settings for sp
as a dictionary.
LibSerialPort.print_port_settings
— Functionprint_port_settings(sp::SerialPort)
Print port settings for sp
.
LibSerialPort.set_read_timeout
— Functionset_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
LibSerialPort.set_write_timeout
— Functionset_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
LibSerialPort.clear_read_timeout
— Functionclear_read_timeout(sp::SerialPort)
Cancel any previous read timeout, such that blocking read operations will now wait without any time limit.
LibSerialPort.clear_write_timeout
— Functionclear_write_timeout(sp::SerialPort)
Cancel any previous write timeout, such that blocking write operations will block without any time limit.
LibSerialPort.Lib.sp_flush
— Functionsp_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.
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).
LibSerialPort.Lib.sp_drain
— Functionsp_drain(port::Port)
sp_drain(SerialPort::Port)
Wait for buffered data to be transmitted.
LibSerialPort.Lib.sp_output_waiting
— FunctionReturns the number of bytes in the output buffer.
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.read
— Methodread(sp::SerialPort)
Return all incoming bytes currently available in the UART as a Vector{UInt8}.
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.
LibSerialPort.nonblocking_read
— Methodnonblocking_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
.
Base.bytesavailable
— Methodbytesavailable(sp::SerialPort)
Return the number of bytes waiting in the input buffer.