# AO_Haptic

Owns the Kode Dot's vibration motor: how a buzz is fed tick by tick, why a tail timer ends it, and the self-test that uses the IMU as witness.

## What it is

**AO_Haptic** makes a Kode Dot vibrate. The motor is a linear resonant actuator, an LRA, driven by an AW86233 chip. Both sit on the antenna board. A buzz on this board is fed: the chip plays from an RTP FIFO and goes back to standby the moment that FIFO runs empty, so the waveform exists only while somebody keeps pushing samples in.

Two writers would mix into noise nobody asked for, so one Active Object owns the whole chip and everything else asks by event.

An Active Object asks for a buzz with `kode_sys_haptic_play_buzz(ms, gain_pct)`, a pattern of on and off segments with `kode_sys_haptic_play_pattern()` or a vibration that lasts until `kode_sys_haptic_stop()` with `kode_sys_haptic_hold()`, and learns that it ended from a published `HAPTIC_DONE_SIG`. A task calls `kode_haptic_play("click")` or `kode_haptic_vibrate()` in `kode.h`. AO_Haptic also runs the production row that proves the motor moves, using the IMU (`sdk/kaos/imu`) as witness: a chip with no motor on its output answers every register write and passes every check it can make on itself.

The chip, the RTP stream and the clamp are on `sdk/kdrv/aw86233`.

## How it is connected

```mermaid
flowchart LR
  app["kode_sys_haptic_play_buzz()<br/>kode_haptic_play()"] -- "HAPTIC_PLAY_REQ_SIG<br/>HAPTIC_STOP_REQ_SIG" --> ao["AO_Haptic<br/>priority 22"]
  con["AO_Console"] -- "HAPTIC_FIELD_REQ_SIG" --> ao
  ao -- "kdrv_aw86233_*()<br/>I2C 0x5A" --> chip["AW86233 + LRA"]
  ao -- "HAPTIC_DONE_SIG" --> app
  ao -- "arm, drain<br/>(the row)" --> imu["AO_Imu"]
  imu -- "IMU_ARMED_SIG<br/>IMU_ENERGY_SIG" --> ao
  class app app
  class ao,con,imu ao
  class chip chip
```

*AO_Haptic and the witness*

AO_Haptic in numbers:

| Thing | Value |
| --- | --- |
| Priority | 22 (`KODE_PRIO_HAPTIC`), the level above AO_Imu |
| Queue | 16 events, the system default |
| Stack | 3072 bytes, the smallest tier |
| Claims | `KBSP_RES_HAPTIC`: the chip at `0x5A` on the antenna PCB and the LRA behind it |
| Buffer | One 64-byte burst, a file-level static |

The priority is above AO_Imu because the feed has a deadline and the IMU's drain does not.

When it is linked, `kode_init()` starts it right after AO_Imu, since the row posts to AO_Imu from its first step. There is no Kconfig gate: something has to own the chip even when the antenna PCB is not fitted. An app links AO_Haptic by calling one of its doors; without one the chip is parked in standby and claimed as `parked(AO_Haptic)`.

```mermaid
stateDiagram-v2
  [*] --> Haptic_absent: no AW86233 found
  Haptic_absent --> Haptic_idle: the chip answers on a look again
  [*] --> Haptic_idle: chip created
  Haptic_idle --> Haptic_playing: HAPTIC_PLAY_REQ_SIG
  Haptic_playing --> Haptic_idle: tail expired, STOP, HAPTIC_DONE_SIG
  Haptic_idle --> Haptic_row: HAPTIC_TEST_REQ_SIG
  Haptic_row --> Haptic_playing: a gain's window is armed
  Haptic_playing --> Haptic_row: that buzz is over
  Haptic_row --> Haptic_idle: verdict
```

*AO_Haptic states*

`Haptic_up` is the parent of `Haptic_idle`, `Haptic_playing` and `Haptic_row` and handles what all three answer alike: `CONFIG_REQ_SIG`, `HAPTIC_FIELD_REQ_SIG` and the stale-timer drops. In `Haptic_absent` the AO logs once that there is nothing to play and answers every later request from there. It looks for the chip again once, 2 s after the boot (`KODE_HAPTIC_RETRY_MS`, on `HAPTIC_RETRY_SIG`), and at the first request, because a NAK on a busy bus is not a board with no antenna PCB. A chip that answers then takes the AO to `Haptic_idle`.

### Standby

Bit 6 of `SYSCTRL2` puts the chip's output stage to sleep, and the chip rests there. Entering `Haptic_playing` clears the bit after a 1 ms wait (`HAPTIC_WAKE_MS`, in the step, with `khal_delay_ms()`). The tail that ends the buzz sets it again.

Every way a buzz can end goes through the tail, failures included, so `play_fail()` arms the tail and does not stop the buzz itself. The I2C interface stays alive and every register keeps its value, so nothing is configured again at wake. Awinic quotes 0.4 ms to start. The wait is a busy-wait and not a timer, because a timer of one 1 ms tick can expire at once and a step that waited for it would push GO past the first feed. A console write of `standby` is overridden by the next buzz.

### The feed

One burst is 64 samples, 5.3 ms of playback at 12 kHz. The step that issues GO wakes the chip, starts RTP, reads `GLB_STATE` until it shows RTP and pushes four bursts (`KODE_HAPTIC_BURSTS_AT_GO`), 21.3 ms of playback, in about 9 ms. The feed then runs every 4 ms (`KODE_HAPTIC_TICK_MS`), so the first one lands about 10 ms after GO with some 11 ms still to play.

The chip's own almost-full flag paces the feed. Each feed reads `GLB_STATE` once, then offers up to two bursts (`KODE_HAPTIC_BURSTS_PER_TICK`), each after a read of `FF_AFS`, and writes none while the flag is set. Two bursts are 2.7 times what the chip plays in a period, so the FIFO fills to the chip's almost-full mark within about 75 ms of GO and stays there, about 124 ms of playback in hand. The chip's oscillator, not the board's clock, sets how fast the FIFO drains, and nothing on the board measures it, so a count kept on the board's clock would run the FIFO dry or overfill it.

When the chip refuses a burst, the phase of the sine wave is put back to its value before the burst. Without that the waveform would jump and the motor would play the jump as a click. A feed that takes nothing is correct, since the chip is ahead of the feed. 200 ms of such feeds in a row (`HAPTIC_STALL_MS`) end the buzz with `KODE_TIMEOUT`. A feed the bus refuses ends it with the bus's error.

A chip found out of RTP while samples are still owed ran dry and went back to standby, and it plays nothing it is given after that. The buzz ends with `KODE_IO_ERROR` and the log says how long after GO the chip left RTP and how much of the buzz was fed.

### The tail

The chip takes samples faster than it plays them, and it holds up to its almost-full mark, about 130 ms. Writing STOP with the last sample would end the buzz early. So after the last sample the feed's tick goes on reading `GLB_STATE`, and the buzz ends the period after the chip has left RTP by itself. The end follows the chip's clock.

The one-shot tail timer is only the bound for a chip that never leaves RTP. It runs for the playback time of the accepted samples less the time since GO, plus what a chip at the slow edge of its tolerance plays on top, plus the drain's allowance. A chip 8 % slow (`KDRV_AW_RATE_TOL_PCT`) plays at 92 % of the rate and takes 100/92 of the length, 8.7 % more, rounded up to the millisecond. The allowance (`HAPTIC_DRAIN_LATE_MS`) is one 4 ms feed period and 2 ms, because the tick reads `GLB_STATE` once a period, the board's clock reads whole milliseconds, and QP counts both timers from the first tick after they are armed, which can come at once. With all three the look that finds the chip out of RTP lands on an earlier tick than the tail, so the order in which QP posts two timers that expire together decides nothing, and a buzz under 50 ms, where 8 % is less than a period, still ends on the chip's clock.

A buzz the bound ends logs a warning that gives the time since GO, the buzz's length, the share of the rate the bound allowed and the allowance: `the chip still read RTP <n> ms after GO, past a <length> ms buzz at 92% of its rate and the drain's 6 ms; stopped it`.

Only the tail's expiry calls `kdrv_aw86233_rtp_end()` and publishes `HAPTIC_DONE_SIG` (`rc`, `samples`, `starved`). `starved` says the feed met the almost-full mark at least once, which every buzz of about 75 ms or longer does; a buzz that ends `KODE_OK` with it set played out whole. After a failure, `samples` is what the chip was fed up to then.

### Busy is refused early

Only AO_Haptic writes the busy flag. `haptic_play_request()` answers `KODE_DENIED` before it allocates an event, so a caller that gets `KODE_OK` has a promise of a buzz. The row holds the flag across its own buzzes. A board with no antenna PCB takes the request and logs once, because a missing chip is a fact about the board and the caller did nothing wrong.

### Stale timers

A timer that is disarmed can still have its expiry in the queue. AO_Haptic counts the timers it stopped, in `Haptic_up`, and drops that many expiries. The count lives in the parent because the stale event arrives after the row has already entered `Haptic_playing`, where a check local to `Haptic_row` would never see it.

### The self-test

`test component=haptic` asked while a buzz plays waits for the buzz to end and then runs. It asks AO_Imu, the witness, to collect windows of accelerometer samples and compares the energy at 235 Hz. The order finds the cause of a fault.

1. **Step 0, is there a chip.** In `Haptic_absent` the row is one record, `result=absent`, and a failed verdict. On a main-board verifier with no antenna PCB that is expected. On a finished unit the fault is the connector between the boards or the chip.
2. **Step 1, the floor.** One 140 ms window (`KODE_HAPTIC_STILL_MS`) with the motor off sets the floor at 235 Hz for the whole run. A floor above 1.2 mg (`KODE_HAPTIC_FLOOR_MAX_X10`, 12 in tenths) means the bench already vibrates, and the row would judge the bench and say nothing about the board.
3. **Step 2, three gains.** It buzzes 200 ms at 25 %, 50 % and 80 % of full scale, weakest first, into a fresh window each. It passes on the first gain whose ratio of driven to floor amplitude reaches 5.2 (`KODE_HAPTIC_TEST_RATIO_X10`, 52).

The records carry the `PLAYCFG2` byte the driver reports back, `0x3F`, `0x7F` and `0xCC`, because the driver clamps at the LRA's rating and then truncates. All levels are integers in tenths of a mg and the ratio is ten times the real one, so the row uses no floating point.

Four conditions end the row with `result=noverdict` and a reason (`mute`, `short` or `loud`):

- a window with fewer than 120 samples (`KODE_HAPTIC_MIN_SAMPLES`);
- a witness that does not answer;
- a buzz the chip did not play through: the bus refused a burst, the FIFO stopped draining or the chip ran dry, so the motor was not driven for the whole window;
- a contaminated floor.

The console shows `timeout` for it, since the row cannot measure and does not blame the motor.

When the chip answers and nothing moves at any gain, the log says the AW86233 answers and the LRA does not move: not fitted, or stuck.

### Resting with the board

With `CONFIG_KODE_LOWPOWER`, AO_Haptic joins the rounds of AO_LowPower as `haptic` (`sdk/kaos/lowpower`). On a round it writes the chip into standby, the state it sits in between buzzes, so a round that finds it there only makes sure. A buzz or the row owns the motor until it ends, so then the round is answered busy with `haptic busy` and no buzz is cut short. A board with no antenna PCB has nothing to rest and answers ready.

Nothing is restored when the board wakes. The next buzz takes the chip out of standby itself, so AO_Haptic listens to the rounds and not to `LOWPOWER_STATE_SIG`.

kodeOS asks for the buzzes of its interface through `kode_sys_haptic_play_buzz()`, as any client does (`internals/gui/buttons-and-gestures`). kgui keeps silent while the microphone or the IMU records, so a buzz is never in what they measure.

## Specifications

### Signals

| Signal | Event | Direction | Meaning |
| --- | --- | --- | --- |
| `HAPTIC_PLAY_REQ_SIG` | `HapticPlayEvt`: `seg_ms`, `n`, `gain_pct`, `hold` | in, posted | A buzz or a pattern of on and off segments, on first, or a hold. The gain is scaled by the `haptic` setting |
| `HAPTIC_STOP_REQ_SIG` | none, a static event | in, posted | End a pattern or a hold early, whoever started it |
| `HAPTIC_FIELD_REQ_SIG` | `HapticFieldReqEvt`: `op`, `field`, `value` | in, posted | Get, set or dump one AW86233 field |
| `HAPTIC_TEST_REQ_SIG` | none | in, posted by AO_Autotest | The production row |
| `LOWPOWER_ROUND_SIG` | `LowPowerRoundEvt` | in, subscribed | With `CONFIG_KODE_LOWPOWER`: the chip to standby, or busy `haptic busy` |
| `CONFIG_REQ_SIG` | `KodeConfigReqEvt` | in | The key `haptic` |
| `IMU_ARMED_SIG`, `IMU_ENERGY_SIG` | from AO_Imu | in | The two replies the row waits for |
| `HAPTIC_TICK_SIG` | none | self, periodic | The feed while a buzz is fed, then the watch for the chip leaving RTP |
| `HAPTIC_TAIL_SIG` | none | self, one-shot | The end of the buzz |
| `HAPTIC_WAIT_SIG` | none | self, one-shot | A reply deadline of the row, or the 140 ms floor window |
| `HAPTIC_RETRY_SIG` | none | self, one-shot | The look again for a chip that did not answer at boot |
| `HAPTIC_DONE_SIG` | `HapticDoneEvt`: `rc`, `samples`, `starved` | out, published | How a buzz ended. Published, not posted, so the asker is not known |
| `HAPTIC_FIELD_SIG` | `HapticFieldEvt`: `op`, `field`, `rc`, `value` | out, published | One field value or the refusal |
| `HAPTIC_TEST_SIG` | `HapticTestEvt` | out, published | Phases `HAPTIC_TEST_ABSENT`, `_FLOOR`, `_GAIN`, `_NOVERDICT`; flags `HAPTIC_TF_PASS`, `_LOUD`, `_SHORT`, `_MUTE` |
| `CONFIG_ANS_SIG` | `KodeConfigAnsEvt` | out | The value of `haptic` |
| `TEST_RESULT_SIG` | named `haptic` | out, published | The verdict |

### Numbers, calls and settings

| Thing | Value |
| --- | --- |
| Buzz length | 1 to 2000 ms (`KODE_SYS_HAPTIC_MAX_MS`) |
| Gain | 0 to 100 %; the driver clamps at the LRA's rating, 80 % |
| Feed | 4 bursts of 64 samples at GO, then a 4 ms tick offering up to 2, paced by `FF_AFS`; stall limit 200 ms |
| Row | 200 ms buzz (`KODE_HAPTIC_TEST_MS`), reply wait 500 ms (`KODE_HAPTIC_REPLY_MS`), console budget 6.36 s (`KODE_HAPTIC_TEST_BUDGET_MS`) |
| Commands | `kode_sys_haptic_play_buzz(ms, gain_pct)`: `KODE_OK` once posted, `KODE_DENIED` for an argument out of range or while a buzz or the row plays, `KODE_NO_RESOURCES` when the pool is dry. `kode_sys_haptic_play_pattern(seg_ms, n, gain_pct)` takes up to 16 segments (`KODE_SYS_HAPTIC_SEGMENTS_MAX`), `kode_sys_haptic_hold(gain_pct)` vibrates until `kode_sys_haptic_stop()` |
| Task calls | `kode_haptic_play(name)` plays "click", "tick", "double", "success", "warning", "error" or a profile added with `kode_haptic_add_profile()`; `kode_haptic_vibrate(on)` holds the motor. Both are in `kode.h` and block |
| Console | `haptic`, `haptic_help`, `haptic_play ms= gain=` (defaults 200 ms at 50 %, the row's own buzz), `test component=haptic`. The only refusal on the wire is `>err code=5 msg=busy` |
| Stored setting | `kset/haptic`, a `u8`, 0 to 100, default 100: a scale on every app and console buzz. At 0 nothing plays and the request still ends with `HAPTIC_DONE_SIG`. The row ignores it |
| Kconfig | None |

## Gotchas

> **WARNING**
>
> **`kode_sys_haptic_play_buzz()` returns `KODE_OK` and nothing moves.** `KODE_OK` means the request is posted. A board with no antenna PCB accepts it and logs once that there is nothing to play, and `haptic=0` plays nothing by design. The AW86233 answers at `0x5A` whether or not an LRA is fitted, so a bus ACK proves nothing about the motor.

> **NOTE**
>
> **A second buzz is refused while one plays, and during the whole row.** The refusal is `KODE_DENIED`. Wait for `HAPTIC_DONE_SIG` before you ask again.

> **NOTE**
>
> **The top gain of the row is 80 %.** That is the LRA's rating, and the row's table stops there so nothing is clamped silently. The ratio falls at a true `0xFF`, a drive this firmware cannot produce.

> **NOTE**
>
> **A row that reads `timeout` did not fail the motor.** `noverdict` records carry the reason: move the bench or fix the witness. Only a measured window that stays quiet at every gain blames the motor.

## Example code

This plays the built-in click once a second. You feel a short pulse every second.

```c
/*
 * haptic_pulse.c - from Kode with love
 *
 * Asks AO_Haptic, the owner of the Kode Dot's vibration motor, for the
 * built-in "click" once a second. You feel a short pulse in your hand every
 * second for as long as the app runs.
 */
#include "kode.h"

/* Bring the system up, then buzz once a second. */
void app_main(void)
{
    kode_init();

    while (1) {
        kode_haptic_play("click");
        kode_delay(1000);
    }
}
```

Compiled against the 0.1.1 SDK with ESP-IDF v6.1 on 2026-11-11. Not run on a Kode Dot.

## In the SDK

- [`components/kaos/haptic`](https://github.com/kodediy/kode-sdk/tree/main/components/kaos/haptic): `haptic_ao.c`, the state machine, the feed and the row.
- [`kode.h`](https://github.com/kodediy/kode-sdk/blob/main/components/kode/include/kode.h): `kode_haptic_play()` and `kode_haptic_vibrate()`.
- [`components/kdrv/motion`](https://github.com/kodediy/kode-sdk/tree/main/components/kdrv/motion): the AW86233 driver beside the IMU's; see `sdk/kdrv/aw86233`.
