---
title: "Peripheral (GPIO / I²C / SPI / UART)"
description: "The most-used header in the SDK. `` provides handle-based wrappers for the four core bus classes: GPIO, I²C, SPI, and UART."
source: https://docs.alplab.ai/sdk/api/peripheral
---

# `<alp/peripheral.h>` — Core Buses

The most-used header in the SDK. `<alp/peripheral.h>` provides handle-based wrappers for the four core bus classes: **GPIO**, **I²C**, **SPI**, and **UART**.

## Header

```c
#include <alp/peripheral.h>
#include <alp/e1m_pinout.h>   // for ALP_E1M_* instance IDs
```

Examples that target both official EVKs can open pins via the portable `BOARD_*` aliases from `<alp/board.h>` instead of raw `ALP_E1M_*` IDs — see [Cross-EVK portability](https://docs.alplab.ai/sdk/board-portability).

## SDK lifecycle

Applications SHOULD call `alp_init()` once at startup, before the first `alp_*_open` call, and `alp_deinit()` at teardown.

```c
if (alp_init() != ALP_OK) {
    return -1;
}

// ... open peripherals, run the app ...

alp_deinit();   // close every open handle first — deinit does not
```

Both are `[ABI-EXPERIMENTAL]` (v0.9 new) and return `alp_status_t`. Today the call is thin — the backend registry is linker-section based and needs no runtime setup, so every current backend works even if you skip it — but future backends (bridge links, clock bring-up, vendor HAL init) are allowed to rely on it, so portable code must not skip it.

- `alp_init()` is **idempotent** (a second successful call is a no-op that returns `ALP_OK`) and safe to call concurrently — an atomic once-guard runs the bring-up exactly once.
- `alp_deinit()` does **not** close peripheral handles for you; close them first. It is idempotent and safe to call without a prior `alp_init()`. Do not race `alp_deinit()` against `alp_init()` or in-flight peripheral calls — the deinit/re-init sequence is single-threaded by contract.

Every `examples/peripheral-io/*` program now calls `alp_init()` first.

## Monotonic time

New in v0.17.0 (`[ABI-EXPERIMENTAL]`), so OS-agnostic code can measure real elapsed time without including a Zephyr or vendor header:

```c
uint64_t alp_uptime_ms(void);
uint64_t alp_uptime_us(void);
```

Both count from an arbitrary, backend-defined epoch (usually boot) and are unaffected by wall-clock or RTC changes — Zephyr's `k_uptime_get()`, Linux `CLOCK_MONOTONIC`, or a calibrated running total on the clockless baremetal fallback. Only the **difference** between two readings in the same process is meaningful. A `uint64_t` millisecond count never wraps in practice, so readings can be compared directly:

```c
uint64_t deadline_ms = alp_uptime_ms() + timeout_ms;
while (alp_uptime_ms() < deadline_ms) {
    /* retry ... */
}
```

`alp_uptime_us()` resolves below a microsecond where the backend has a 64-bit cycle counter (e.g. AEN, with `CONFIG_TIMER_HAS_64BIT_CYCLE_COUNTER`), otherwise one kernel tick. A reading can lag real time by up to one resolution step, so a deadline wait built on it may run short by that much on a tick-resolution backend.

## Pixel formats

`alp_pixfmt_t` is shared by the display, camera, GUI and JPEG classes. Values are only ever appended:

| Value | Name | Notes |
|-------|------|-------|
| `0` | `ALP_PIXFMT_MONO_VLSB` | 1 bpp, vertical bytes (SSD1306 native). |
| `1` | `ALP_PIXFMT_RGB565` | |
| `2` | `ALP_PIXFMT_RGB888` | |
| `3` | `ALP_PIXFMT_ARGB8888` | |
| `4` | `ALP_PIXFMT_YUV420_PLANAR` | I420; for [`<alp/jpeg.h>`](https://docs.alplab.ai/sdk/api/jpeg) input. |
| `5` | `ALP_PIXFMT_NV12` | Semi-planar 4:2:0; for `<alp/jpeg.h>` input. |
| `6` | `ALP_PIXFMT_GREY8` | v0.17.0. 8 bpp mono, one byte per pixel (e.g. OV9281). |
| `7` | `ALP_PIXFMT_RAW8` | v0.17.0. Sensor-native 8-bit raw: Bayer CFA or mono. |
| `8` | `ALP_PIXFMT_RAW10` | v0.17.0. Sensor-native 10-bit raw, **unpacked** to one 16-bit little-endian sample per pixel (high 6 bits zero) — never the CSI-2 packed form — so the row stride is always `width * 2`. |

`ALP_PIXFMT_RAW8` / `RAW10` do not encode a Bayer order: a frame uses the **sensor's** native order (BGGR / GBRG / GRBG / RGGB), and there is no runtime query for it. Take it from the board or camera-shield documentation and hardcode it, as you do the frame size.

## Default-initialiser macros

v0.10 adds an `ALP_*_CONFIG_DEFAULT(id)` macro next to (almost) every config struct in the SDK. Each takes the config's **identity** field as its only argument and fills every other field with a canonical default, so callers set only what they actually want to change — and new fields added to a config struct in a later release pick up a sane default automatically instead of silently reading as zero.

```c
alp_i2c_config_t cfg = ALP_I2C_CONFIG_DEFAULT(ALP_E1M_I2C0);
cfg.bitrate_hz = 400000u;               // fast-mode
alp_i2c_t *bus = alp_i2c_open(&cfg);
```

For `<alp/peripheral.h>` itself:

| Macro                               | Identity arg | Defaults                                                         |
|-------------------------------------|--------------|------------------------------------------------------------------|
| `ALP_I2C_CONFIG_DEFAULT(id)`        | `bus_id`     | `bitrate_hz = 100000` — I²C standard-mode, the universally-safe rate. |
| `ALP_I2C_TARGET_CONFIG_DEFAULT(id)` | `bus_id`     | `own_addr_7bit = 0`, `on_write = NULL`, `on_read = NULL`, `on_stop = NULL`, `user = NULL`. |
| `ALP_SPI_CONFIG_DEFAULT(id)`        | `bus_id`     | `freq_hz = 1000000`, `mode = ALP_SPI_MODE_0`, `bits_per_word = 8`, `cs_pin_id = ALP_SPI_NO_CS`. |
| `ALP_SPI_TARGET_CONFIG_DEFAULT(id)` | `bus_id`     | `mode = ALP_SPI_MODE_0`, `bits_per_word = 0` (i.e. default 8). The /CS line is driven by the external controller, so no `cs_pin_id` is configured on the target side. |
| `ALP_UART_CONFIG_DEFAULT(id)`       | `port_id`    | `baudrate = 115200`, `data_bits = 8`, `stop_bits = 1`, `parity = ALP_UART_PARITY_NONE` — i.e. 115200 8N1. |

The other classes carry their own — `ALP_ADC_CONFIG_DEFAULT`, `ALP_PWM_CONFIG_DEFAULT`, `ALP_CAN_CONFIG_DEFAULT`, `ALP_WDT_CONFIG_DEFAULT`, and so on — documented on each class's page.

:::note[The zero defaults on `ALP_I2C_TARGET_CONFIG_DEFAULT` are deliberate]
`own_addr_7bit`, `on_write`, and `on_read` are all mandatory, so they default to a **"you must set this" sentinel**. `alp_i2c_target_open` rejects a reserved address (`0x00`-`0x07` / `0x78`-`0x7F`) or a `NULL` callback with `ALP_ERR_INVAL` — and `0x00` falls in the reserved range, so a caller who forgets to set `own_addr_7bit` fails loudly at `open()` rather than silently claiming an unintended address. `on_stop` and `user` are genuinely optional.
:::

### C++ compound-literal contract

Every `ALP_*_CONFIG_DEFAULT` expands to a **compound literal**, so it works both as an initialiser and as a bare expression:

```c
alp_i2c_t *bus = alp_i2c_open(&ALP_I2C_CONFIG_DEFAULT(ALP_E1M_I2C0));
```

Compound literals are standard C (through C23). In **C++** they are a GCC/Clang extension — which is fine for the SDK's own toolchains, but on a compiler that rejects them in C++ (notably MSVC), initialise the config's fields individually instead.

## Status-code strings

v0.10 adds two lookup helpers, both **generated from the `alp_status_t` enum** by `scripts/gen_status_strings.py` — the enum is the single source of truth, so no status code can drift out of sync with its string.

```c
alp_status_t rc = alp_i2c_write(bus, addr, data, len);
if (rc != ALP_OK) {
    printf("i2c write failed: %s (%s)\n",
           alp_status_name(rc), alp_status_description(rc));
}
```

| Call                              | Returns                                                                 |
|-----------------------------------|-------------------------------------------------------------------------|
| `alp_status_name(alp_status_t s)` | The stable **symbolic name** — `"ALP_OK"`, `"ALP_ERR_INVAL"`, … A pure `.rodata` table lookup, always compiled in. A value outside the declared `ALP_STATUS_ENUM_FLOOR`..`ALP_OK` range returns the documented fallback `"ALP_STATUS_UNKNOWN"`. |
| `alp_status_description(alp_status_t s)` | A short **human-readable description**, generated from each enum member's doc comment. Intended for logs and diagnostics. |

Neither ever returns `NULL`.

`alp_status_description`'s string table is compiled in only when `CONFIG_ALP_STATUS_DESCRIPTIONS` is enabled (**default y**); a footprint-sensitive build can turn it off to drop the table while `alp_status_name` stays available. When compiled out, the function still returns a documented fallback string rather than `NULL`.

Use these for logs and diagnostics — **not** for programmatic branching. Switch on the `alp_status_t` value itself for that.

## GPIO

```c
alp_gpio_t *led = alp_gpio_open(ALP_E1M_GPIO_IO1);
if (led == NULL) {
    int err = alp_last_error();
    return err;
}
alp_gpio_configure(led, ALP_GPIO_OUTPUT, ALP_GPIO_PULL_NONE);

alp_gpio_write(led, 1);    // drive high
alp_gpio_write(led, 0);    // drive low

bool value;
alp_gpio_read(led, &value);

alp_gpio_close(led);
```

### Input with pull-up + IRQ

```c
alp_gpio_t *btn = alp_gpio_open(ALP_E1M_GPIO_IO0);
alp_gpio_configure(btn, ALP_GPIO_INPUT, ALP_GPIO_PULL_UP);

void on_press(alp_gpio_t *pin, void *user) { /* ... */ }

alp_gpio_irq_enable(btn, ALP_GPIO_EDGE_FALLING, on_press, NULL);
```

### Configuration

`alp_gpio_open(pin_id)` takes the studio-resolved pin id directly (there is no config struct); direction and pull are set afterwards with `alp_gpio_configure(pin, dir, pull)`.

| Argument  | Type              | Notes                                                              |
|-----------|-------------------|-------------------------------------------------------------------|
| `pin_id`  | `uint32_t`        | Passed to `alp_gpio_open()`. Use `ALP_E1M_GPIO_IO<N>` from `<alp/e1m_pinout.h>`. |
| `dir`     | `alp_gpio_dir_t`  | `ALP_GPIO_INPUT` / `ALP_GPIO_OUTPUT`.                             |
| `pull`    | `alp_gpio_pull_t` | `ALP_GPIO_PULL_NONE` / `ALP_GPIO_PULL_UP` / `ALP_GPIO_PULL_DOWN`. |

## I²C

```c
alp_i2c_t *bus = alp_i2c_open(&(alp_i2c_config_t){
    .bus_id     = ALP_E1M_I2C0,
    .bitrate_hz = 400000u,        // 100k / 400k / 1M / 3.4M (per-SoC)
});

uint8_t buf[2] = { 0x00, 0x42 };
alp_i2c_write(bus, /* addr */ 0x50, buf, sizeof(buf));

uint8_t reg = 0x00;
uint8_t rx[16];
alp_i2c_write_read(bus, 0x50, &reg, 1, rx, sizeof(rx));

alp_i2c_close(bus);
```

### Config struct

| Field         | Type             | Notes                                                |
|---------------|------------------|------------------------------------------------------|
| `bus_id`      | `uint32_t`       | `ALP_E1M_I2C0` … `ALP_E1M_I2C<N>`.                   |
| `bitrate_hz`  | `uint32_t`       | Bus speed. Not checked against `<alp/soc_caps.h>`: the Zephyr backend maps any rate ≥ 1 MHz to Fast-mode Plus; the Yocto backend ignores it. |

### Common operations

| Function                       | Description                                       |
|--------------------------------|---------------------------------------------------|
| `alp_i2c_write(bus, a, buf, n)`        | Write `n` bytes.                                  |
| `alp_i2c_read(bus, a, buf, n)`         | Read `n` bytes.                                   |
| `alp_i2c_write_read(bus, a, tx, n, rx, m)` | Repeated-start: write `n`, read `m`.          |

## I²C target (slave) mode

:::info[`[ABI-EXPERIMENTAL]` — v0.9 new]
The target-mode surface may change in any minor release; it is not covered by the stable-ABI contract that the controller-mode I²C calls carry.
:::

Target mode makes *this* MCU answer on the bus as an addressable device — a "register-mapped peripheral" from the external controller's point of view. The callbacks are **byte-granular** and mirror the wire protocol, so a register-file slave is a ~20-line state machine on top of them. All three callbacks run in **ISR context** — keep the work minimal (update a state machine, stash into a `volatile` buffer) and defer anything substantive to a thread / workqueue.

```c
#include <alp/peripheral.h>

static volatile uint8_t regs[16];

static void on_write(uint8_t byte, void *user) { /* controller sent a byte */ }

static alp_status_t on_read(uint8_t *byte, void *user) {
    *byte = 0x42;      // byte to drive back onto the bus
    return ALP_OK;     // any error NAKs / ends the transfer
}

static void on_stop(void *user) { /* controller ended the transaction */ }

alp_i2c_target_t *tgt = alp_i2c_target_open(&(alp_i2c_target_config_t){
    .bus_id        = ALP_E1M_I2C0,
    .own_addr_7bit = 0x42,          // must be 0x08..0x77
    .on_write      = on_write,      // required
    .on_read       = on_read,       // required
    .on_stop       = on_stop,       // optional; may be NULL
    .user          = NULL,
});
if (tgt == NULL) {
    int err = alp_last_error();     // ALP_ERR_INVAL / NOSUPPORT / NOT_READY / ...
    return err;
}

// ... callbacks fire as the controller talks to us ...

alp_i2c_target_close(tgt);          // no callback fires after this returns
```

### Config struct

| Field           | Type                        | Notes                                                          |
|-----------------|-----------------------------|----------------------------------------------------------------|
| `bus_id`        | `uint32_t`                  | Studio-resolved bus instance id (same id space as `alp_i2c_open`). |
| `own_addr_7bit` | `uint8_t`                   | Address this target answers on. **Must be `0x08`..`0x77`** — the reserved 7-bit ranges `0x00`–`0x07` / `0x78`–`0x7F` are rejected with `ALP_ERR_INVAL`. |
| `on_write`      | `alp_i2c_target_write_cb_t` | `void(uint8_t byte, void *user)` — a byte arrived. **Required.** |
| `on_read`       | `alp_i2c_target_read_cb_t`  | `alp_status_t(uint8_t *byte, void *user)` — supply the outgoing byte; return `ALP_OK` to continue, any error to NAK / end. **Required.** |
| `on_stop`       | `alp_i2c_target_stop_cb_t`  | `void(void *user)` — STOP condition. Optional; may be `NULL`.   |
| `user`          | `void *`                    | Forwarded to every callback.                                   |

- `alp_i2c_target_open(cfg)` returns an opaque `alp_i2c_target_t *`, or `NULL` with `alp_last_error()` set — `ALP_ERR_INVAL` (NULL cfg/callbacks, reserved address), `ALP_ERR_NOSUPPORT` (backend or controller driver has no target mode), `ALP_ERR_NOT_READY` (bus alias unset), `ALP_ERR_BUSY` (address slot already taken), `ALP_ERR_OUT_OF_RANGE`, `ALP_ERR_NOMEM`.
- Prime any state the callbacks read (register files, counters) **before** calling — the callbacks start firing as soon as `open` returns.
- `alp_i2c_target_close(tgt)` is `void`, idempotent on `NULL`, and guarantees no callback fires after it returns.

:::note[Availability]
Requires controller-driver target support (Zephyr: `CONFIG_I2C_TARGET` plus a driver that implements `target_register`). Drivers without it fail `open()` with `ALP_ERR_NOSUPPORT` (or `ALP_ERR_NOT_READY` when the bus alias is unset) — applications must degrade cleanly. On `native_sim` the emulated controller accepts the registration but nothing external ever drives it, so callbacks never fire there.
:::

### Register-file I²C target

`<alp/i2c_regfile.h>` ships the classic register-file state machine once, so applications stop re-pasting it on top of the byte-granular target callbacks. It exposes a caller-owned RAM buffer as a register-mapped I²C target:

- controller write, byte 0 → latches the register pointer (taken modulo the file length, EEPROM-style wraparound);
- controller write, bytes 1.. → store into the buffer at the pointer, auto-increment with wraparound;
- controller read → streams the buffer from the pointer, auto-increment with wraparound;
- STOP → re-arms "next written byte is the pointer" for the following transaction.

The buffer is caller-owned: firmware publishes state with plain (`volatile`) stores and observes controller writes by reading it back — no extra API between the ISR callbacks and the application thread. Availability tracks `alp_i2c_target_open` exactly, and it is `[ABI-EXPERIMENTAL]` (v0.9 new).

```c
#include <alp/i2c_regfile.h>

static volatile uint8_t regs[32];
regs[0] = 0xA5;                       // prime an ID register BEFORE open

alp_i2c_regfile_t *rf;
alp_status_t rc = alp_i2c_regfile_open(ALP_E1M_I2C0, /* own_addr_7bit */ 0x42,
                                       regs, sizeof(regs), &rf);
if (rc != ALP_OK) {
    return rc;   // ALP_ERR_INVAL / NOSUPPORT / NOT_READY / NOMEM
}
```

**→ [`<alp/i2c_regfile.h>`](https://docs.alplab.ai/sdk/api/i2c-regfile)** documents the full surface: write windows, traffic stats, the ISR-context rules, and the availability contract.

## SPI

```c
alp_spi_t *spi = alp_spi_open(&(alp_spi_config_t){
    .bus_id        = ALP_E1M_SPI1,
    .freq_hz       = 8000000u,
    .mode          = ALP_SPI_MODE_0,
    .bits_per_word = 8,
    .cs_pin_id     = ALP_E1M_GPIO_IO5,
});

uint8_t tx[4] = { 0xAA, 0x55, 0xC3, 0x3C };
uint8_t rx[4];
alp_spi_transceive(spi, tx, rx, sizeof(tx));

alp_spi_close(spi);
```

:::note[DMA and the data cache]
`tx` and `rx` may live in ordinary cacheable memory. Where a backend moves data over a DMA master that does not snoop the CPU cache, the driver cleans `tx` before and invalidates `rx` after the transfer. The one thing left to you is **granularity**: cache maintenance works on whole lines, so if `rx` shares a cache line with other live data, a CPU write to that neighbour during the transfer can be lost by the post-transfer invalidate. Give a DMA-sized `rx` buffer its own cache line(s). `alp_spi_transceive()` returns `ALP_ERR_INVAL` when `len` exceeds the per-transfer ceiling.
:::

### Config struct

| Field            | Type                | Notes                                              |
|------------------|---------------------|----------------------------------------------------|
| `bus_id`         | `uint32_t`          | `ALP_E1M_SPI0` … `ALP_E1M_SPI<N>`.                 |
| `freq_hz`        | `uint32_t`          | SCLK frequency.                                    |
| `mode`           | `alp_spi_mode_t`    | `ALP_SPI_MODE_0` … `ALP_SPI_MODE_3`.               |
| `bits_per_word`  | `uint8_t`           | Typically 8; some SoCs support 16/32.              |
| `cs_pin_id`      | `uint32_t`          | Controller-driven chip-select pin, or `ALP_SPI_NO_CS` for none. |

## SPI target (slave) mode

:::info[`[ABI-EXPERIMENTAL]` — v0.9 new]
The target-mode surface may change in any minor release; it is not covered by the stable-ABI contract that the controller-mode SPI calls carry.
:::

Target mode makes this MCU the **clocked** side of the bus: the external controller owns SCK + /CS and decides when — and how many — bytes move. Because SPI is full-duplex and the target cannot see a command before it must respond within the *same* transfer, the surface is **transfer-based**: preload a TX response, block until the controller clocks a transfer, inspect what arrived, preload the next reply. No `cs_pin_id` is configured on the target side — the controller drives /CS.

```c
#include <alp/peripheral.h>

alp_spi_target_t *tgt = alp_spi_target_open(&(alp_spi_target_config_t){
    .bus_id        = ALP_E1M_SPI1,
    .mode          = ALP_SPI_MODE_0,   // must match the controller (0..3)
    .bits_per_word = 8,                // 0 defaults to 8; max 32
});
if (tgt == NULL) {
    int err = alp_last_error();        // ALP_ERR_INVAL / NOSUPPORT / NOT_READY / ...
    return err;
}

uint8_t tx[4] = { 0xDE, 0xAD, 0xBE, 0xEF };
uint8_t rx[4];
size_t  rx_len;
alp_status_t rc = alp_spi_target_transceive(tgt, tx, rx, sizeof(tx), &rx_len,
                                            UINT32_MAX);   // wait forever
// rc == ALP_OK: the controller clocked rx_len bytes (0..sizeof(tx))

alp_spi_target_close(tgt);             // returns ALP_ERR_BUSY if a transfer is armed
```

### Config struct

| Field           | Type             | Notes                                                              |
|-----------------|------------------|--------------------------------------------------------------------|
| `bus_id`        | `uint32_t`       | Studio-resolved bus instance id.                                   |
| `mode`          | `alp_spi_mode_t` | CPOL/CPHA — **must match the external controller**. Validated to `0..3`. |
| `bits_per_word` | `uint8_t`        | Usually 8. `0` defaults to 8; max 32. `> 32` rejects with `ALP_ERR_INVAL`. Must match the controller. |

### `alp_spi_target_transceive`

```c
alp_status_t alp_spi_target_transceive(alp_spi_target_t *bus,
                                       const uint8_t    *tx,      // NULL = drive idle pattern
                                       uint8_t          *rx,      // NULL = discard input
                                       size_t            len,     // bytes; must be > 0
                                       size_t           *rx_len,  // bytes clocked; may be NULL
                                       uint32_t          timeout_ms);
```

Stages one target-side transfer and waits for the controller to clock it. `tx` is driven onto data-out; whatever the controller drives lands in `rx`. The controller may clock **fewer** bytes than `len` — `rx_len` reports how many actually moved, always **in bytes** regardless of `bits_per_word`.

- **`len` must be `> 0`.** Unlike controller-mode `alp_spi_transceive` (where `len == 0` is a no-op `ALP_OK`), a target cannot stage a zero-length transfer — it returns `ALP_ERR_INVAL`.
- **Timeouts.** `timeout_ms == UINT32_MAX` blocks until the controller completes the transfer (deasserts /CS) — call from a thread that may wait indefinitely. A finite `timeout_ms` bounds the wait, but on the Zephyr backend it needs `CONFIG_SPI_ASYNC`; a finite timeout on a sync-only build returns `ALP_ERR_NOSUPPORT` rather than silently blocking forever.
- **After a timeout the transfer stays armed.** SPI slave hardware has no portable cancel, so after `ALP_ERR_TIMEOUT` the handle answers `ALP_ERR_BUSY` — and `alp_spi_target_close` refuses teardown — until the external controller finally clocks the pending transfer. **Keep `tx` / `rx` valid** until a later call on the handle stops returning `ALP_ERR_BUSY`.
- **One transfer at a time.** A second thread calling while a transceive is in flight gets `ALP_ERR_BUSY`.

Returns `ALP_OK` / `ALP_ERR_INVAL` / `ALP_ERR_NOT_READY` / `ALP_ERR_BUSY` / `ALP_ERR_TIMEOUT` / `ALP_ERR_IO` / `ALP_ERR_NOSUPPORT`.

`alp_spi_target_close(tgt)` now returns `alp_status_t`: `ALP_OK` on release (or a `NULL` / already-closed no-op), or `ALP_ERR_BUSY` — freeing nothing — while a thread is blocked in a transceive on the handle or a timed-out transfer is still armed. Retry after the in-flight transfer completes.

:::note[Availability]
Requires controller-driver slave support (patchy across Zephyr SoC drivers; needs `CONFIG_SPI_SLAVE`). Backend-level absence fails `open()` with `ALP_ERR_NOSUPPORT` / `ALP_ERR_NOT_READY`; driver-level absence instead surfaces on the **first** `transceive` as `ALP_ERR_NOSUPPORT` (the Zephyr backend cannot probe it at open). On `native_sim` the emulated controller accepts a slave-mode open but nothing external ever clocks a transfer — degrade cleanly and bound your waits either way.
:::

## UART

```c
alp_uart_t *uart = alp_uart_open(&(alp_uart_config_t){
    .port_id     = ALP_E1M_UART0,
    .baudrate    = 115200u,
    .data_bits   = 8,
    .stop_bits   = 1,
    .parity      = ALP_UART_PARITY_NONE,
});

const char *msg = "hello\n";
alp_uart_write(uart, (const uint8_t *)msg, strlen(msg));

uint8_t buf[64];
alp_uart_read(uart, buf, sizeof(buf), 100);   // up to 64 bytes, 100 ms timeout

alp_uart_close(uart);
```

### Flow control

New in v0.17.0, `alp_uart_config_t` carries `alp_uart_flow_t flow_control`:

| Value | Meaning |
|-------|---------|
| `ALP_UART_FLOW_NONE` | No flow control (default; what `ALP_UART_CONFIG_DEFAULT` sets). |
| `ALP_UART_FLOW_RTS_CTS` | 4-wire hardware flow control. |
| `ALP_UART_FLOW_XON_XOFF` | In-band software flow control; many drivers reject it. |

A backend that cannot honour a non-`NONE` request fails the whole `alp_uart_open()` with `ALP_ERR_NOSUPPORT` instead of silently opening without flow control. Where the driver can read its applied setting back (Zephyr `uart_config_get`, Linux `tcgetattr`), an accepted-but-not-applied request is also caught.

:::caution[`ALP_OK` does not prove the wires are there]
The check covers the backend's configuration layer, not the board. Per-SoM RTS/CTS pad routing is not emitted yet, so on a board whose devicetree does not route RTS/CTS to that UART, `alp_uart_open()` can return `ALP_OK` for `ALP_UART_FLOW_RTS_CTS` with no flow control on the line.
:::

### Port selection on Linux

On Yocto / Linux, `port_id` selects a tty family by range: `0..99` → `/dev/ttyS<n>`, `100..199` → `/dev/ttyAMA<n - 100>`, `200..299` → `/dev/ttyUSB<n - 200>`, `300..399` → `/dev/ttySC<n - 300>` (Renesas SCIF, e.g. RZ/V2N). Anything `>= 400` fails with `ALP_ERR_INVAL`. On Zephyr it is the backend's UART index.

### `alp_uart_read` timeouts

`timeout_ms` bounds the **whole call**, not each byte. On timeout with a partial fill, `alp_uart_read` returns `ALP_OK` with the partial bytes in `data` — but the caller gets no count of how many, so read in smaller chunks (or pair with the RX ring buffer below) when a partial-fill count matters.

**`timeout_ms == 0` is a single non-blocking poll**: it returns immediately with `ALP_ERR_TIMEOUT` if no byte is already available. This is the portable contract, and v0.10 fixes the Zephyr backend to honour it — it previously treated `timeout_ms == 0` as *wait forever*, the exact opposite of the documented behaviour.

### RX ring buffer (interrupt-driven)

When the consumer can't keep up, enable a caller-supplied ring buffer:

```c
#include <alp/peripheral.h>

static uint8_t rx_ring_storage[256];
alp_uart_rx_ringbuf_t *ring =
    alp_uart_rx_ringbuf_attach(uart, rx_ring_storage, sizeof(rx_ring_storage));
if (ring == NULL) {
    return alp_last_error();   // ALP_ERR_NOSUPPORT on builds without the ring path
}

// Later, pull what's there without polling:
size_t got;
alp_uart_rx_ringbuf_pop(ring, buf, sizeof(buf), &got);

// At teardown, detach before closing the port:
alp_uart_rx_ringbuf_detach(ring);
```

`CONFIG_ALP_SDK_UART_RX_RINGBUF=y` enables the ring path. See the `uart-rx-ringbuf` example.

`alp_uart_rx_ringbuf_detach()` is idempotent (a second detach is a no-op) and blocks until any in-flight `alp_uart_rx_ringbuf_pop()` / `_count()` on the same handle returns, so the backing store can be reused or freed once it returns.

### `NULL` and closed handles

Since v0.17.0 the GPIO, I²C, SPI and UART data calls document one consistent split: `ALP_ERR_NOT_READY` for a `NULL` or closed handle, `ALP_ERR_INVAL` for a `NULL` buffer with a non-zero length. `ALP_ERR_NOT_READY` itself now reads "the handle is not in a state to perform this operation" rather than "not initialised".

## Capability validation

Some `_open()` calls cross-check the requested config against `<alp/soc_caps.h>`, for example the ADC resolution below. Not every field is gated: the I²C `bitrate_hz` is not checked, and DAC / I3C admission goes through the backend registry, with the selected backend bound-checking the channel or bus. Example failure:

| Config                          | Result on a 12-bit SoC                                |
|---------------------------------|-------------------------------------------------------|
| `alp_adc_open(.resolution_bits = 16)` | `NULL` + `alp_last_error() == ALP_ERR_OUT_OF_RANGE` |

## E1M portability

Instance IDs come from `<alp/e1m_pinout.h>` and are portable across every conformant SoM. The companion `ALP_E1M_<CLASS>_COUNT` macros tell you how many instances the E1M standard guarantees:

```c
for (size_t i = 0; i < ALP_E1M_I2C_COUNT; i++) {
    alp_i2c_t *bus = alp_i2c_open(&(alp_i2c_config_t){
        .bus_id     = ALP_E1M_I2C0 + i,
        .bitrate_hz = 100000u,
    });
    /* ... */
}
```

Apps that stay within the portable bound work on every E1M SoM, present and future.

## See also

- [Quick start](https://docs.alplab.ai/sdk/quick-start) — concrete walk-through
- [Pinout](https://docs.alplab.ai/hardware/pinout) — signal classes per pad
- [`<alp/pwm.h>`](https://docs.alplab.ai/sdk/api/pwm) — PWM channels
- [`<alp/adc.h>`](https://docs.alplab.ai/sdk/api/adc) — analog sampling
- [Examples: gpio-button-led](https://docs.alplab.ai/sdk/examples/gpio-button-led)
- [Examples: i2c-scanner](https://docs.alplab.ai/sdk/examples/i2c-scanner)
