Standard library · Hardware

hw.serial

Serial ports on the host: TTL and RS232 adapters, microcontrollers and modems, with baud, data bits, parity, stop bits and timeouts.

import hw.serial

hw.serial talks to serial ports: USB to TTL and RS232 adapters, Arduino and ESP boards, GPS receivers, modems and lab instruments. A port is a Port value; every call takes it and never throws, so a failure is an answer you check with IsOpen.

PlatformHow the port is reached
Linux, macOS, BSDA device file such as /dev/ttyUSB0, /dev/ttyACM0 or /dev/cu.usbserial-1, configured raw through termios
WindowsA COM handle opened with CreateFile; use COM3 or \\.\COM12 (the prefix is added when missing)
Other systemsnone: Supported is false

Things to know:

•

Format. Open uses 8N1. OpenFormat takes the baud rate, 5 to 8 data bits, a parity (PARITY_NONE, PARITY_EVEN or PARITY_ODD) and 1 or 2 stop bits. Valid checks a format without a device, and an invalid one makes OpenFormat return a closed port.

•

Timeouts are in milliseconds. ReadByte and ReadLine wait at most that long. ReadByte returns -1 on a timeout or a closed port; ReadLine returns what it has read so far, possibly empty.

•

You own the line. ReadLine returns a heap string without the line ending. Free it with mem.Free(line as void*) when you are done.

•

Close once you are done. Close restores the terminal settings and is safe on a closed port.

•

Testing without hardware. On Linux a pseudo terminal can stand in for a port: create the master with posix_openpt, call grantpt and unlockpt, then open ptsname of the master with Open. What the program writes can be read from the master and what the test writes to the master arrives as serial input.

Opening a port

Check the format with Valid, open the port and test IsOpen before using it. A missing device or a missing permission (on Linux, membership of the dialout group) both show up as a closed port.

hw-serial-guide-open.salam
Try it
import hw.serial

func main:
    if not serial.Valid(115200, 8, serial.PARITY_NONE, 1):
        println "bad format"
        ret 1
    end
    p := serial.Open("/dev/ttyUSB0", 115200)
    if not serial.IsOpen(p):
        println "cannot open", p.path
        ret 0
    end
    println "opened", p.path, "at", p.baud
    ret 0
end
Output
cannot open /dev/ttyUSB0

Reading lines

Devices that talk in text, such as sensors and modems, end each message with a line break. ReadLine collects one message per call and returns an empty string when nothing arrives before the timeout. This example feeds a pseudo terminal so it runs without hardware.

hw-serial-guide-lines.salam
Try it
import hw.serial
import mem

if SALAM_OS_LINUX:
    extern:
        func posix_openpt(flags: int): int
        func grantpt(fd: int): int
        func unlockpt(fd: int): int
        func ptsname(fd: int): str
        func write(fd: int, buf: str, n: u64): i64
    end
end

func main:
    if SALAM_OS_LINUX:
        m := posix_openpt(2)
        grantpt(m)
        unlockpt(m)
        mut p := serial.Open(ptsname(m), 9600)
        write(m, "temp=21.5\r\ntemp=21.7\r\n", 22 as u64)
        repeat 3 in i:
            line := serial.ReadLine(p, 200)
            println i, line
            mem.Free(line as void*)
        end
        serial.Close(p)
    else:
        println 0, "temp=21.5"
        println 1, "temp=21.7"
        println 2, ""
    end
end
Output
0 temp=21.5
1 temp=21.7
2

Types

Port

#
struct Port

An open or failed serial port. Pass it by value to the I/O functions; only Close takes it by reference.

NameTypeDescription
pathstr = ""The device path or COM name the port was opened with.
handlei64 = -1The file descriptor (Linux, macOS, BSD) or the Windows handle, or -1 when the port is not open.
okbool = falseTrue when the port opened and is not closed. IsOpen returns this value.
baudint = 0The speed in bits per second that was asked for.
hw-serial-Open.salam
Try it
import hw.serial

func main:
    mut p := serial.Open("/dev/does-not-exist", 9600)
    println serial.IsOpen(p), p.ok, p.path, p.baud, p.handle
    serial.Close(p)
    q := serial.OpenFormat("/dev/does-not-exist", 19200, 7, serial.PARITY_ODD, 2)
    println serial.IsOpen(q), q.baud
    r := serial.OpenFormat("/dev/ttyUSB0", 9600, 9, serial.PARITY_NONE, 1)
    println serial.IsOpen(r), r.baud
end
Output
false false /dev/does-not-exist 9600 -1
false 19200
false 9600

Constants and variables

PARITY_NONE

#
const PARITY_NONE: i32 = 0

No parity bit (0). The usual choice and the default of Open.

hw-serial-Valid.salam
Try it
import hw.serial

func main:
    println serial.Valid(9600, 8, serial.PARITY_NONE, 1)
    println serial.Valid(115200, 7, serial.PARITY_EVEN, 2)
    println serial.Valid(0, 8, serial.PARITY_NONE, 1)
    println serial.Valid(9600, 4, serial.PARITY_NONE, 1)
    println serial.Valid(9600, 8, 3, 1)
    println serial.Valid(9600, 8, serial.PARITY_ODD, 3)
    println serial.PARITY_NONE, serial.PARITY_EVEN, serial.PARITY_ODD
    println serial.Supported()
end
Output
true
true
false
false
false
false
0 1 2
true

PARITY_EVEN

#
const PARITY_EVEN: i32 = 1

Even parity (1): the parity bit makes the number of one bits even.

The example for this item is shown with the ones above: hw-serial-Valid.salam

PARITY_ODD

#
const PARITY_ODD: i32 = 2

Odd parity (2): the parity bit makes the number of one bits odd.

The example for this item is shown with the ones above: hw-serial-Valid.salam

Functions

IsOpen

#
func IsOpen(p: Port): bool

True when the port is open and ready for I/O.

The example for this item is shown with the ones above: hw-serial-Open.salam

Supported

#
func Supported(): bool

Whether this system has a serial backend: true on Linux, macOS, BSD and Windows.

The example for this item is shown with the ones above: hw-serial-Valid.salam

Valid

#
func Valid(baud: int, data_bits: int, parity: int, stop_bits: int): bool

Checks a line format without touching any device: a positive baud, 5 to 8 data bits, parity 0 to 2 and 1 or 2 stop bits.

The example for this item is shown with the ones above: hw-serial-Valid.salam

OpenFormat

#
func OpenFormat(path: str, baud: int, data_bits: int, parity: int, stop_bits: int): Port

Opens a port with an explicit format. An invalid format or a device that cannot be opened returns a Port for which IsOpen is false, and nothing is left open.

The example for this item is shown with the ones above: hw-serial-Open.salam

Open

#
func Open(path: str, baud: int): Port

Opens a port as 8N1 (8 data bits, no parity, 1 stop bit) at the given baud. A failure returns a Port for which IsOpen is false.

The example for this item is shown with the ones above: hw-serial-Open.salam

Close

#
func Close(p &: Port)

Closes the port and puts the terminal settings back. Closing a port that is not open does nothing, so it is safe to call twice.

The example for this item is shown with the ones above: hw-serial-Open.salam

WriteBytes

#
func WriteBytes(p: Port, data: void*, n: int): bool

Writes n bytes from a buffer and returns true when all of them were written. Use it for binary data.

hw-serial-Lines.salam
Try it
import hw.serial
import mem

if SALAM_OS_LINUX:
    extern:
        func posix_openpt(flags: int): int
        func grantpt(fd: int): int
        func unlockpt(fd: int): int
        func ptsname(fd: int): str
        func write(fd: int, buf: str, n: u64): i64
        func read(fd: int, buf: void*, n: u64): i64
    end
end

func main:
    if SALAM_OS_LINUX:
        m := posix_openpt(2)
        grantpt(m)
        unlockpt(m)
        mut p := serial.Open(ptsname(m), 9600)
        println serial.IsOpen(p)
        println serial.Write(p, "AT\r\n")
        println serial.WriteByte(p, 33)
        println serial.WriteBytes(p, "BC" as void*, 2)
        serial.Flush(p)
        buf := mem.AllocateZeroed(64 as u64)
        defer mem.Free(buf)
        println read(m, buf, 63 as u64)
        write(m, "OK 7\r\nrest", 10 as u64)
        line := serial.ReadLine(p, 500)
        println line
        mem.Free(line as void*)
        println serial.ReadByte(p, 200)
        println serial.ReadByte(p, 50)
        println serial.ReadByte(p, 50)
        println serial.ReadByte(p, 50)
        println serial.ReadByte(p, 50)
        serial.Close(p)
        println serial.IsOpen(p)
    else:
        println true
        println true
        println true
        println true
        println 7
        println "OK 7"
        println 114
        println 101
        println 115
        println 116
        println -1
        println false
    end
end
Output
true
true
true
true
7
OK 7
114
101
115
116
-1
false

Write

#
func Write(p: Port, text: str): bool

Writes a whole string to the port and returns true when every byte was written.

The example for this item is shown with the ones above: hw-serial-Lines.salam

WriteByte

#
func WriteByte(p: Port, value: int): bool

Writes one byte (0 to 255) and returns true on success.

The example for this item is shown with the ones above: hw-serial-Lines.salam

ReadByte

#
func ReadByte(p: Port, timeout_ms: int): int

Reads one byte and returns it as 0 to 255, or -1 when the port is closed or nothing arrives within the timeout in milliseconds.

The example for this item is shown with the ones above: hw-serial-Lines.salam

ReadLine

#
func ReadLine(p: Port, timeout_ms: int): str

Reads until a newline or until the timeout in milliseconds runs out and returns the text without the line ending. The result is a heap string that the caller owns and must free.

The example for this item is shown with the ones above: hw-serial-Lines.salam

Flush

#
func Flush(p: Port)

Waits until everything written has left the port, and drops input that was not read yet.

The example for this item is shown with the ones above: hw-serial-Lines.salam