gpio

The gpio module drives hardware on single-board computers such as the Raspberry Pi: digital pins (with internal pull-up/down and blocking edge waits), hardware PWM, and the I²C and SPI buses. Pins and buses are referenced by an integer handle. Import it with import gpio.

Digital pins

FunctionSignatureDescription
initgpio.init() → boolInitialize the GPIO subsystem
opengpio.open(name: string) → intOpen a pin by name (e.g. "GPIO18"); -1 if unknown
namegpio.name(h: int) → stringThe pin’s name ("" if unknown)
outputgpio.output(h: int, initLevel?: int) → boolSet as output; optional initial level 0/1 (defaults low)
inputgpio.input(h: int, pull?: string) → boolSet as input; pull is "up", "down", or "float"
readgpio.read(h: int) → intRead the level (0 or 1)
writegpio.write(h: int, level: int) → boolDrive the level (0 or 1)
waitEdgegpio.waitEdge(h: int, edge: string, timeoutMs: int) → boolBlock for an edge ("rising", "falling", "both"); false on timeout
closegpio.close(h: int) → boolRelease the pin

gpio.pwm

Hardware PWM on the BCM2835 channels (GPIO12/13/18/19 on the Pi).

FunctionSignatureDescription
setgpio.pwm.set(h: int, dutyPct, freqHz) → boolStart PWM at a duty cycle (percent) and frequency
stopgpio.pwm.stop(h: int) → boolStop PWM on the pin

gpio.i2c

FunctionSignatureDescription
opengpio.i2c.open(busNum: int) → intOpen an I²C bus; -1 on error
writegpio.i2c.write(h: int, addr: int, bytes: string) → boolWrite bytes to a device
readgpio.i2c.read(h: int, addr: int, n: int) → stringRead n bytes from a device
txgpio.i2c.tx(h: int, addr: int, tx: string, nRead: int) → stringCombined write-then-read with a repeated start (register-pointer sensors)
closegpio.i2c.close(h: int) → boolClose the bus

gpio.spi

FunctionSignatureDescription
opengpio.spi.open(bus: int, cs: int, speedHz: int, mode: int) → intOpen an SPI device; -1 on error
transfergpio.spi.transfer(h: int, txBytes: string) → stringFull-duplex transfer; returns the received bytes
closegpio.spi.close(h: int) → boolClose the device

Example

import gpio
import time

gpio.init()

// blink an LED on GPIO18
let led = gpio.open("GPIO18")
gpio.output(led)

let i = 0
while i < 10 {
    gpio.write(led, 1)
    time.timer.sleep(250)
    gpio.write(led, 0)
    time.timer.sleep(250)
    i += 1
}

// read a button on GPIO23 with an internal pull-up, wait for a press
let btn = gpio.open("GPIO23")
gpio.input(btn, "up")
if gpio.waitEdge(btn, "falling", 5000) {
    println("pressed")
}

gpio.close(led)
gpio.close(btn)
Standard library · View as Markdown · llms-full.txt