---
title: "nanopb Encode/Decode"
description: "native_sim build + run PASSED locally, but this has not been verified on real silicon (no bench / HiL sweep)."
source: https://docs.alplab.ai/sdk/examples/nanopb-encode-decode
---

# `nanopb-encode-decode`

:::warning[`[UNTESTED]`]
`native_sim` build + run PASSED locally, but this has not been verified on real silicon (no bench / HiL sweep).
:::

A protobuf message encode → buffer → decode round-trip with [nanopb](https://github.com/nanopb/nanopb) 0.4.9 (zlib licence) — protocol buffers sized for an MCU.

Source: [`examples/connectivity/nanopb-encode-decode/`](https://github.com/alplabai/alp-sdk/tree/main/examples/connectivity/nanopb-encode-decode).

## What it does

1. `pb_encode()` a `DeviceStatus { int32 uptime_s; string device_id }` into a caller-owned buffer.
2. `pb_decode()` it back into a fresh struct.
3. Asserts the round-trip.

Everything is in RAM and every buffer is caller-owned — nanopb never allocates.

:::note[The generated sources are checked in]
`device_status.pb.c` / `.pb.h` are pre-generated and committed, because there is no `protoc` in this build environment. Do not hand-edit them — regenerate from the `.proto` instead.
:::

Unlike most of the library examples, nanopb is a real fetched west module (`modules/lib/nanopb`), not a vendored stub. Its `zephyr/module.yml` declares `cmake-ext` / `kconfig-ext` glue that the SDK does not wire centrally, so the example's `CMakeLists.txt` compiles the runtime sources (`pb_encode.c` / `pb_decode.c` / `pb_common.c`) directly via `${ZEPHYR_NANOPB_MODULE_DIR}`. `libraries: [nanopb]` emits `CONFIG_ALP_NANOPB_SW=y`.

## `board.yaml`

```yaml
libraries:
  - name: nanopb
    cores: [m55_hp]

som:
  sku: E1M-AEN801

preset: e1m-evk

cores:
  m55_hp:
    app: ./src
    peripherals: []

diagnostics:
  log_level: info
```

This example does no I/O — swap `som.sku` to any SoM/preset pair and it still builds; the round-trip is entirely in RAM.

## Expected output

```
[nanopb-encode-decode] encoded 14 bytes
[nanopb-encode-decode] decoded uptime_s=42 device_id="e1m-aen801"
[nanopb-encode-decode] round trip OK
[nanopb-encode-decode] done
```

## See also

- [`jsmn-json-parse`](https://docs.alplab.ai/sdk/examples/jsmn-json-parse) — the text-serialisation counterpart
- [Examples overview](https://docs.alplab.ai/sdk/examples/overview)
