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
Section titled “Import”import serial from "@std/net/serial"Exports
Section titled “Exports”| Name | Kind | Description |
|---|---|---|
Port | struct | Serial port connection type. |
serial.Port
Section titled “serial.Port”Opens a serial port.
Arguments:
| Name | Type | Default | Description |
|---|---|---|---|
device | string | none | Serial device path. |
baud | int | 9600 | Baud 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()port.write
Section titled “port.write”Writes text data to the serial port.
Arguments:
| Name | Type | Description |
|---|---|---|
data | string | Data to send. |
Returns: void
port.write("hello from writer\r")port.read
Section titled “port.read”Reads data from the serial port.
Arguments:
| Name | Type | Description |
|---|---|---|
timeoutMs | int | Read 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.
port.close
Section titled “port.close”Closes the serial port.
Returns: void
port.close()Prefer defer after opening a port.
const port = serial.Port("/dev/ttyUSB0", 9600)defer port.close()Reader Example
Section titled “Reader Example”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)}Writer Example
Section titled “Writer Example”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)}Function Syntax Note
Section titled “Function Syntax Note”Use -> only when describing a function value type.
let reader: fn(int) -> stringWhen 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()}