Hardware with Jennifer: GPIO, I2C, SPI and serial

Jennifer

Blink an LED, read a button, a sensor, an ADC and a microcontroller from a Raspberry Pi™, and test all of it on a laptop.

November 2026, by @mplx.
Based on Jennifer 0.27.0

Powered by Jennifer's Cantrip - Markdown into slide decks, https://github.com/jennifer-language/cantrip
1 / 22

Four ways to talk to hardware

BusWiresGood for
GPIOone per signalLEDs, buttons, relays (through a driver)
I2CSDA, SCL, sharedslow sensors: temperature, humidity, light
SPIMOSI, MISO, SCLK, one CE per chipfast chips: ADCs, displays, flash
Serial (UART)TX, RX, GNDa microcontroller, GPS, a modem

Rule of thumb: one pin, GPIO; a sensor, I2C; speed, SPI; another computer, serial.

2 / 22

What Jennifer gives you

NameKindRuns on
import "gpio.j" as gpio;module, sysfs /sys/class/gpioboth binaries
use gpio;library, /dev/gpiochipNjennifer on Linux
use i2c; use spi; use serial;libraries, /dev + ioctljennifer on Linux
3 / 22

Switch it on, then get permission

# /boot/firmware/config.txt (Raspberry Pi OS), then reboot
dtparam=i2c_arm=on
dtparam=spi=on
enable_uart=1
sudo usermod -aG gpio,i2c,spi,dialout "$USER"   # log in again
serial.open: /dev/ttyS0: open /dev/ttyS0: permission denied
4 / 22

Blink an LED

use time;
import "gpio.j" as gpio;

def const LED as int init 17; # BCM 17 = header pin 11

gpio.setup(LED, gpio.OUT);
defer gpio.release(LED);
for (def i in 0..3) {
    gpio.write(LED, 1);
    time.sleep(time.fromMilliseconds(500));
    gpio.write(LED, 0);
    time.sleep(time.fromMilliseconds(500));
}
5 / 22

Pin numbers, and the run without a Pi

$ mkdir mock; JENNIFER_GPIO_BASE=$PWD/mock jennifer run blink.j
$ grep -r . mock
mock/export:17
mock/gpio17/direction:out
mock/gpio17/value:0
mock/unexport:17
6 / 22

Read a button: poll and debounce

gpio.setup(BUTTON, gpio.IN); # to GND, pull-up: pressed reads 0
def last as int init gpio.read(BUTTON);
def presses as int init 0;
while ($presses < 3) {
    time.sleep(time.fromMilliseconds(20));
    def now as int init gpio.read(BUTTON);
    if ($now != $last) {
        time.sleep(time.fromMilliseconds(20)); # bounce over?
        if (gpio.read(BUTTON) == $now) {
            $last = $now; # on 0: count and print a press
        }
    }
}
7 / 22

Pressing a button made of files

mkdir -p mock/gpio27; echo 1 > mock/gpio27/value
sh press.sh &   # writes 0, then 1, three times, 0.3 s apart
JENNIFER_GPIO_BASE=$PWD/mock jennifer run button.j
press 1
press 2
press 3
8 / 22

I2C: one bus, many addresses

use i2c;

def bus as i2c.Bus init i2c.open("/dev/i2c-1", 0x44);
i2c.close($bus);
9 / 22

SHT31: start a measurement, read six bytes

export func measure(bus as i2c.Bus) {
    def cmd as bytes;
    $cmd[] = 0x24; # single shot, high repeatability,
    $cmd[] = 0x00; # no clock stretching
    i2c.write($bus, $cmd);
    time.sleep(time.fromMilliseconds(20)); # up to about 15 ms
    return decode(i2c.read($bus, 6));
}
T high, T low, CRC, RH high, RH low, CRC
10 / 22

SHT31: checksum and conversion

func word(frame as bytes, at as int) {
    if (crc8($frame[$at..$at + 2]) != $frame[$at + 2]) {
        throw Error{kind: "sht31", message: "CRC mismatch at {$at}"};
    }
    return ($frame[$at] << 8) | $frame[$at + 1];
}

export func decode(frame as bytes) {
    def c as float init -45.0 + 175.0 * word($frame, 0) / 65535;
    def h as float init 100.0 * word($frame, 3) / 65535;
    return Reading{celsius: $c, humidity: $h};
}
11 / 22

SPI: an MCP3008 analog-to-digital converter

export func request(ch as int) {
    def tx as bytes;
    $tx[] = 0x01;              # start bit
    $tx[] = (0x08 | $ch) << 4; # single-ended, channel ch
    $tx[] = 0x00;              # clocks the low byte in
    return $tx;
}

export func value(rx as bytes) {
    return (($rx[1] & 0x03) << 8) | $rx[2];
}
12 / 22

SPI: read the channels

def dev as spi.Device init spi.open("/dev/spidev0.0"); # CE0
spi.configure($dev, 0, 1000000); # mode 0, 1 MHz
defer spi.close($dev);
for (def ch in 0..2) {
    def raw as int init adc.read($dev, $ch); # spi.transfer
    io.printf("ch%d %d|pad=4  %f|prec=2 V\n", $ch, $raw,
        $raw * 3.3 / 1024);
}
ch0  512  1.65 V
ch1 1023  3.30 V
13 / 22

Serial: a line protocol to a microcontroller

func ask(port as serial.Port, cmd as string) {
    serial.write($port, encoding.encode("utf-8", $cmd + "\n"));
    serial.setReadDeadline($port, 500); # the whole reply
    def buf as bytes;
    while (not binary.contains($buf, NL)) {
        $buf = binary.concat($buf, serial.read($port, 64));
    }
    serial.setReadDeadline($port, 0);
    return strings.trim(encoding.decode("utf-8", $buf));
}
14 / 22

Serial: answers and timeouts

def port as serial.Port init serial.open(os.getEnv("MCU_TTY"), 115200);
defer serial.close($port);
serial.flush($port);
PING -> PONG
TEMP? -> TEMP 21.4
LED 1 -> OK
HELLO -> ERR unknown command
SLEEP -> timeout: serial.read: read timed out
15 / 22

Testing without hardware

python3 fakemcu.py $PWD/ttyMCU &   # symlink to the pty's other end
MCU_TTY=$PWD/ttyMCU jennifer run mcu.j
16 / 22

Decoders are just functions

func testCrcDatasheetVector() {
    testing.assertEqual(crc8(frame([0xbe, 0xef])), 0x92);
}

func testDecode() {
    def f as bytes init frame([0x66, 0x66, 0x93, 0x80, 0x00, 0xa2]);
    def r as Reading init decode($f);
    testing.assertEqual(math.round($r.celsius * 10.0) / 10.0, 25.0);
}
$ jennifer test sht31_test.j
PASS testCrcDatasheetVector (0 ms)
PASS testDecode (0 ms)
17 / 22

Safety: the pins are not forgiving

18 / 22

Project: a temperature logger

def const LED as int init 17;
def const LIMIT as float init 22.0;

func sample(port as serial.Port) {
    def reply as string init ask($port, "TEMP?");
    if (not strings.startsWith($reply, "TEMP ")) {
        throw Error{kind: "mcu", message: "bad reply: {$reply}"};
    }
    return convert.toFloat($reply[5..]);
}

def port as serial.Port init serial.open(os.getEnv("MCU_TTY"), 115200);
gpio.setup(LED, gpio.OUT);
19 / 22

Project: the loop

while (true) { # lint-disable: L105
    def now as string init time.format(time.now(), "%H:%M:%S");
    try {
        def t as float init sample($port);
        gpio.write(LED, convert.toInt($t > LIMIT));
        fs.appendString("temps.csv", "{$now},{$t}\n");
        io.printf("%s %v C, LED %d\n", $now, $t, gpio.read(LED));
    } catch (e) {
        serial.flush($port); # drop a late reply
        io.eprintf("%s %s: %s\n", $now, $e.kind, $e.message);
    }
    time.sleep(time.fromSeconds(1));
}
20 / 22

Project: a run

$ MCU_TTY=$PWD/ttyMCU JENNIFER_GPIO_BASE=$PWD/mock jennifer run logger.j
13:25:03 21.4 C, LED 0
13:25:04 21.7 C, LED 0
13:25:05 22.0 C, LED 0
13:25:06 timeout: serial.read: read timed out
13:25:08 22.3 C, LED 1
13:25:09 22.6 C, LED 1
$ cat mock/gpio17/value
1
21 / 22

Take-aways and read more

22 / 22