---
title: "Counter / Quadrature Encoder"
description: "Generic up/down counter API plus quadrature-encoder mode."
source: https://docs.alplab.ai/sdk/api/counter
---

# `<alp/counter.h>` — Counters and Encoders

Generic up/down counter API plus quadrature-encoder mode.

## Counter

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

alp_counter_t *cnt = alp_counter_open(&(alp_counter_config_t){
    .counter_id = ALP_E1M_COUNTER0,   /* published ids are 0..3 — but which of
                                       * them this SoM actually serves is
                                       * per-backend; always check for NULL. */
});
if (cnt == NULL) {
    int err = alp_last_error();       /* see the failure-mode table below */
    return err;
}

alp_counter_start(cnt);
uint32_t value;
alp_counter_get_value(cnt, &value);
alp_counter_close(cnt);
```

## `alp_counter_open()` failure modes

`alp_counter_open()` returns an open handle on success, or **NULL** with `alp_last_error` set to one of:

| Code                              | Cause                                                                                                                           |
|-----------------------------------|---------------------------------------------------------------------------------------------------------------------------------|
| `ALP_ERR_INVAL`                   | NULL `cfg`; or, **on the Yocto backend only**, a `counter_id` large enough to truncate the `/sys/bus/counter` path it builds.     |
| `ALP_ERR_NOT_PRESENT_ON_THIS_SOC` | No counter backend registered for this silicon.                                                                                  |
| `ALP_ERR_NOT_IMPLEMENTED`         | The selected backend declares no open op — not reachable through any shipped backend today.                                      |
| `ALP_ERR_NOMEM`                   | The handle pool is exhausted (`CONFIG_ALP_SDK_MAX_COUNTER_HANDLES` counters already open).                                        |
| `ALP_ERR_NOT_READY`               | DT alias unresolved / device not ready on the generic Zephyr backend; or, on V2N/V2M, the GD32 supervisor bus not yet configured. |
| `ALP_ERR_BUSY`                    | The V2N/V2M supervisor mutex is contended.                                                                                       |
| `ALP_ERR_NOSUPPORT`               | `counter_id` is a valid E1M-X connector identity (see [`<alp/e1m_x_pinout.h>`](#e1m-x-counter-identities-are-padless)) that this SoM's backend doesn't serve — e.g. **the V2N/V2M bridge serves only `ALP_E1M_X_COUNTER0`**. |

## E1M-X counter identities are padless

`ALP_E1M_X_COUNTER0 = 0u`, `ALP_E1M_X_COUNTER1 = 1u`, `ALP_E1M_X_COUNTER2 = 2u`, `ALP_E1M_X_COUNTER3 = 3u`.

These four ids are **padless**: no e1m-spec connector pad backs them (`metadata/e1m/pinout-x-v1.json` carries no counter entry, unlike the pinned classes). They are an E1M-X **namespace convention**, *not* a claim tied to the header's `N < ALP_E1M_X_<CLASS>_COUNT` portability-bound block — counter has **no such bound macro**.

They are also **not a per-SoM promise**: a different SoM in this family may serve all four.

:::caution[Branch on "open failed", not on one code]
A published id this SoM does not serve **never** reports `ALP_ERR_INVAL` — a published id is not a bad argument — but the status it *does* report is **per-backend**:

| Backend source                          | Status for an id it doesn't serve                                                                          |
|-----------------------------------------|--------------------------------------------------------------------------------------------------------------|
| `src/backends/counter/gd32_bridge.c`    | `ALP_ERR_NOSUPPORT` for an id at or beyond `GD32G553_BRIDGE_COUNTER_CHANNELS`. This is the V2N/V2M path, which serves `ALP_E1M_X_COUNTER0` **only**. |
| `src/backends/counter/zephyr_drv.c`     | Its `alp-counter<N>` alias table is a fixed **four** entries, so every published identity is inside it, and a board with no alias for one reports `ALP_ERR_NOT_READY` (alias unresolved) — **not** `ALP_ERR_NOSUPPORT`. |
| `src/backends/counter/yocto_drv.c`      | No id range of its own — it probes `/sys/bus/counter` and maps the POSIX errno.                              |

Code that tests for one specific status will mis-handle a SoM swap. Test that the open failed.
:::

Cross-reference: alp-sdk `docs/portability.md` §4.5, alp-sdk#1242.

## `alp_counter_capabilities()->channel_count`

`channel_count` is a property of the **active backend**, not of the handle you pass in.

It is populated **only by the V2N/V2M GD32 bridge** today (`src/backends/counter/gd32_bridge.c`), which serves only `ALP_E1M_X_COUNTER0` of the four E1M-X connector identities. It reads **0 on every other backend**:

- the generic Zephyr backend has no single machine-readable source for its DT-resolved instance count,
- the SW fallback accepts every id,
- the Yocto Counter sysfs ABI exposes no queryable device count.

:::warning[A 0 means "not reported by this backend", NOT "serves no counters"]
Treating `channel_count == 0` as "this backend has no counters" will make you skip a counter that is present and working.
:::

Since v0.17.0 the descriptor can tell the two cases apart: `channel_count == 0` alongside `ALP_INSTANCE_CAP_REPORTED` in `flags` means "serves none", while `REPORTED` clear means "not reported" (see [Capabilities](https://docs.alplab.ai/sdk/api/capabilities#alp_instance_cap_t-flags)). **No counter backend sets `REPORTED` yet**, so on every counter backend today a zero still means "not reported" — but check the flag rather than assuming, so your code keeps working once a backend adopts it.

On V2N/V2M the count is discoverable only **after** `ALP_E1M_X_COUNTER0` opens successfully — and that open can itself fail (`ALP_ERR_NOT_READY` if the GD32 supervisor's SPI/I2C bus isn't configured, `ALP_ERR_BUSY` on a contended supervisor mutex), in which case the served count cannot be queried at all. A higher id opened directly fails with `ALP_ERR_NOSUPPORT`.

## Alarms

```c
void on_alarm(alp_counter_t *c, uint32_t ticks, void *user) { /* fired */ }

alp_counter_set_alarm(cnt, /* ticks_from_now */ 1000000, on_alarm, NULL);
```

At most one alarm per handle. Replacing an already-armed alarm on the same handle is **backend-dependent** since v0.17.0 — some backends replace it silently, others return `ALP_ERR_BUSY` — so call `alp_counter_cancel_alarm()` first when you don't know the backend. `alp_counter_close()` cancels any armed alarm as part of teardown (best effort; not atomic with a callback already in flight). Several counter calls can now also return `ALP_ERR_NOSUPPORT`.

## Quadrature encoder

```c
alp_qenc_t *qenc = alp_qenc_open(&(alp_qenc_config_t){
    .encoder_id     = ALP_E1M_ENC0,        /* 0..ALP_E1M_ENC_COUNT-1 (= 4) */
    .pulses_per_rev = 24,              /* mechanical resolution, informational */
});

int32_t position;
alp_qenc_get_position(qenc, &position);

/* Reset accumulated count back to 0: alp_qenc_reset_position(qenc); */

alp_qenc_close(qenc);
```

The decoder hardware runs continuously — `alp_qenc_open()` just gives you a handle to query the accumulated count. `position` is signed: sign carries direction since the last reset, magnitude is the raw pulse count.

On the E1M-X V2N family the four quadrature encoders are owned by the GD32 supervisor; the host driver routes `alp_qenc_*` through [`<alp/chips/gd32g553.h>`](https://docs.alplab.ai/sdk/chips) without the app having to change anything.

## Default-initialiser macros

| Macro                            | Defaults                                                        |
|----------------------------------|------------------------------------------------------------------|
| `ALP_COUNTER_CONFIG_DEFAULT(id)` | Sets `counter_id` from `id`; the struct carries no other field.   |
| `ALP_QENC_CONFIG_DEFAULT(id)`    | Sets `encoder_id` from `id` plus `pulses_per_rev = 0`.            |

See [the shared macro contract](https://docs.alplab.ai/sdk/api/peripheral#default-initialiser-macros) for the C++ compound-literal caveat that applies to every `ALP_*_CONFIG_DEFAULT`.

## See also

- [Examples: counter-alarm, qenc-readout](https://docs.alplab.ai/sdk/examples/overview)
