Skip to content

Serial

The @std/net/serial package provides serial port access.

import serial from "@std/net/serial"
const port = serial.Port("/dev/ttyUSB0", 9600)
defer port.close()
port.write("hello\r")
const out = port.read(2000)
println(out)
import serial from "@std/net/serial"
NameKindDescription
PortstructSerial port connection type.

Opens a serial port.

Arguments:

NameTypeDefaultDescription
devicestringnoneSerial device path.
baudint9600Baud rate.

Returns: Port

import serial from "@std/net/serial"
const port = serial.Port("/dev/ttyUSB0", 9600)
defer port.close()

Use the default baud rate:

const port = serial.Port("/dev/ttyUSB0")
defer port.close()

Writes text data to the serial port.

Arguments:

NameTypeDescription
datastringData to send.

Returns: void

port.write("hello from writer\r")

Reads data from the serial port.

Arguments:

NameTypeDescription
timeoutMsintRead timeout in milliseconds.

Returns: string

const out = port.read(2000)
if out != "" {
println("Reader got:", out)
}

Internally, read uses a read timeout and reads up to a buffer of data.

Closes the serial port.

Returns: void

port.close()

Prefer defer after opening a port.

const port = serial.Port("/dev/ttyUSB0", 9600)
defer port.close()
import serial from "@std/net/serial"
const reader = serial.Port("/dev/pts/4", 9600)
defer reader.close()
while true {
const out = reader.read(2000)
if out != "" {
println("Reader got:", out)
}
sleep(1000)
}
import serial from "@std/net/serial"
const writer = serial.Port("/dev/pts/1", 9600)
defer writer.close()
while true {
writer.write("hello from writer\r")
println("Writer sent: hello from writer")
sleep(1000)
}

Use -> only when describing a function value type.

let reader: fn(int) -> string

When writing a function implementation, put the return type after the parameter list.

fn readOnce(timeoutMs: int) string {
return conn.read(timeoutMs)
}

For a function that returns nothing, use void.

fn closeConn() void {
conn.close()
}