The Sensor Hub

Watching a motion sensor with the main processor drains a battery in hours. A tiny always-on chip does the same watching on tens of microamps and wakes the big one only when it matters.

Learn how a device splits its work between a small chip that never sleeps and a large processor that sleeps almost always: the power arithmetic, the wake-up threshold, the gesture state machine and the batch that carries the data across.

Pick who watches the sensor, then drag the gestures per hour. Watch the current on two rails, one for the big processor and one for the always-on part. Then we build, piece by piece, everything underneath.

You need a rough idea of what a processor and a sensor are and a little C for the code. We build the rest from zero. The lessons on FIFO, watermark and timestamps and sleep and the battery budget come first, and each is taught again inline.

Built from primary sources: the ST LSM6DSV16X, TDK ICM-42670-P and Bosch BHI260AP datasheets, the ST STM32L476 datasheet and the Android sensors documentation. Every source is listed in the Field Guide. The devices are models, not silicon.

Who watches the sensor?

20

The always-on numbers are datasheet values: STM32L476 at 100 µA/MHz run and 1.1 µA Stop 2, LSM6DSV16X accelerometer at 17 µA and 60 Hz. The big processor (100 mA awake, 2 mA suspended, 6 ms per wake, 500 ms per gesture) and the 300 mAh battery are illustrative, not from any datasheet.

Chapter 0

Why a Device Needs a Second, Tiny Computer

See why no polling interval can both save the battery and catch a short motion, and meet the chip that solves it

You lift your phone off the desk. Before your thumb touches anything, the screen lights up. Something inside noticed the lift, decided it meant “the owner wants to look”, and woke the display. It did this while the phone sat in your pocket all morning, and the battery still lasted the day.

Who noticed? Not the big processor that runs your apps. That processor draws roughly a hundred milliamps when it works. If it watched the motion sensor all day, the battery would be flat by lunch. A much smaller chip noticed. It never sleeps, and it costs about a thousand times less current.

Two computers, two jobs

Most modern devices hold two kinds of processor. The application processor (AP) is the large one. It runs the operating system, the screen, the network stack and your apps. It is fast and hungry. Think of it as a chef in a busy kitchen: brilliant, expensive, and best left to rest until there is an order.

The sensor hub is the small one. It is a tiny microcontroller (a whole computer on one chip: processor, memory and peripherals) that stays awake all the time on a trickle of current. Think of it as the host at the restaurant door. The host does not cook. The host watches the door, and calls the chef only when a real guest arrives.

The word always-on names this role. The hub is on when the device looks off. It reads the motion sensor, applies simple rules, and turns a stream of raw numbers into a rare event: “picked up”, “step taken”, “tapped twice”. The AP sees only the events.

Sometimes the hub is a separate chip. Sometimes it is a small core beside the AP on the same die. Sometimes it is inside the sensor package itself. The three parts we study later show all three shapes. The idea is the same in each: move the watching to the cheapest thing that can do it.

The polling dilemma

A fair question: why not let the AP sleep and wake now and then to look? This is polling: checking a sensor on a timer, the way you might glance at a pot every few minutes. Try it. A lift of the phone lasts about 300 ms in the model below. The AP checks every T milliseconds.

Poll on a timer

The purple curve is the average current of the processor. The red curve is the share of 300 ms lifts the checks miss. Drag the check interval and look for a setting that is low on both. There is none.

100 ms

Illustrative processor: 2 mA suspended, 100 mA awake, 6 ms awake per check. A check catches a 300 ms lift for certain when the interval is 300 ms or less, and with probability 300 divided by the interval above that.

The curves cross in a sad place. Check every 100 ms and you catch every lift, but the processor is awake 6% of the time and draws about 8 mA. Check every 2,000 ms and the current falls near the 2 mA floor, but you miss 85 of every 100 lifts. A fast sensor event and a sleeping processor do not mix.

The hub breaks the trade. It checks every sample, because its checks cost microamps. The AP checks never. Chapter 2 shows the arithmetic. For now, keep the result from the hero: in the model, the hub design runs on about 2.3 mA where polling needs 100 mA.

What you will be able to do

By the end you can read a datasheet and say what the sensor itself can do while everything else sleeps. You can work out the average current of a design on paper, set a wake-up threshold and say what it will miss, write a gesture as a small state machine, and size a batch so the AP wakes rarely and loses nothing. You can also say what goes wrong when the hub and the AP disagree about time.

Every device on this page is a model. Real silicon draws what it draws. Each chapter ends its device with an On real hardware note: a board and one measurement to repeat, so the model never has the last word.

The road

  1. Two computers in one device: what the AP and the hub are, with datasheet numbers.
  2. The current ledger: average current as charge per second, and why wake-ups dominate.
  3. The wake-up threshold: the first filter lives in the sensor, and it has a price.
  4. Gestures as state machines: tilt, raise to wake and the hold time.
  5. Batching: FIFO, watermark, report latency and the interrupt count.
  6. Two FIFOs and a sleeping processor: wake-up and non-wake-up events.
  7. The hub’s firmware: run to sleep, interrupts and cycles per sample.
  8. Sensors that classify: decision trees inside the sensor.
  9. When the hub and the AP disagree: timestamps, drift and lost data.
  10. Field Guide: the numbers, a checklist, the core code, sources.
A phone must notice a 300 ms lift and also last a day. Why does polling with the main processor fail?

Chapter 1

Two Computers in One Device

Meet the application processor and the sensor hub, learn the sleep states that make a hub possible, and compare four real parts

Open a fitness band and you find a small board. On it sits one chip that talks to your phone and draws the screen. Next to it sits another chip, much smaller, that counts your steps while the first chip is asleep. When you shake your wrist, the small chip taps the big one on the shoulder. The big one wakes, draws the time, and goes back to sleep.

That split is the whole idea of a sensor hub. This chapter makes it exact. We name the parts, learn what “asleep” means for a processor, and compare four real parts with their datasheet numbers.

What “asleep” means

A processor is a clocked machine. Every tick of its clock (a steady pulse that sets the pace) moves charge through millions of tiny switches. More ticks per second means more charge per second, so more current. The first rule of low power follows: a processor that does not tick uses almost nothing.

Chips use this rule in steps. In run mode the processor executes code. In sleep mode it stops the clock to the processor core but keeps the rest alive, so any interrupt can restart it within a few cycles. In stop mode it stops most clocks, keeps memory contents, and wakes more slowly. In standby it powers off almost everything and keeps only a few wake pins. Deeper means lower current and slower wake. The lesson on sleep and the battery budget covers this in full.

Take a real chip. The ST STM32L476 is an Arm Cortex-M4 microcontroller with up to 80 MHz clock and 128 KB of SRAM. Its datasheet lists 100 µA per MHz in run mode, 1.1 µA in Stop 2, and 120 nA in Standby with five wake pins. At 16 MHz, run mode costs 16 × 100 µA = 1.6 mA. Stop 2 costs 1.1 µA. That is 1,450 times less.

The big processor sleeps too, but differently. Its operating system suspends it to a state where the RAM stays powered. In this lesson’s model that costs 2 mA. A chip that costs 2 mA while asleep cannot be the always-on part. The hub must cost far less than the AP’s own sleep.

Where the hub lives

A hub can sit in three places. Each is a trade between freedom and current.

A separate microcontroller gives you total freedom. You write all the firmware in C. The STM32L476 is a typical choice. The cost is a chip, a board area and a bus to the sensor.

A smart sensor puts a small programmable core inside the sensor package. The Bosch BHI260AP pairs a six-axis IMU with a 32-bit core called Fuser2. Its datasheet says the core runs at 20 MHz in Long Run mode and 50 MHz in Turbo mode, and draws 950 µA at 20 MHz while running the CoreMark benchmark. With the gyroscope and accelerometer suspended and the core in deep sleep, the whole chip draws 7.3 µA. The datasheet also says the core can boot from a host as small as a Cortex-M0 or as large as a multicore AP, or run alone from attached flash.

A sensor with built-in logic gives you the least freedom and the lowest current. You configure fixed functions with registers. The ST LSM6DSV16X has hardware for wake-up, tilt, free-fall and step detection, plus up to 8 finite state machine programs and a machine learning core. The TDK ICM-42670-P has fixed APEX functions: pedometer, tilt, wake on motion and significant motion. You set thresholds. You do not write code.

Compare five places to watch

Each row shows two bars on a log scale: the lighter bar is the current when the part rests, the solid bar is the current when it works. Pick a part to read what you can change on it.

Datasheet values: STM32L476 Stop 2 1.1 µA and run 100 µA/MHz at 16 MHz; BHI260AP deep sleep 7.3 µA and core 950 µA at 20 MHz; LSM6DSV16X power-down 2.6 µA and accelerometer 17 µA at 60 Hz; ICM-42670-P sleep 3.5 µA and six-axis low-noise mode 0.55 mA. The working numbers measure different things, so compare the shape, not the bars. The AP row is illustrative.

Read the picture as a staircase. The processor at the top rests at 2 mA. Every always-on option rests below 10 µA, at least 200 times lower. That gap is what the hub buys.

The worked sum

Add up a real always-on rail. Use the STM32L476 as hub, reading an LSM6DSV16X at 60 Hz. The sensor costs 17 µA. Chapter 7 shows the hub’s own work costs 36 µA at 6,000 cycles per sample, and its sleep costs about 1.1 µA. So 17 + 36 + 1.1 = 54 µA, or 0.054 mA. The AP’s suspended floor is 2 mA. The whole hub rail is about 37 times smaller than the AP’s own sleep.

The failure you will meet first

Here is the symptom. A prototype loses 5% of its battery an hour in a drawer. A power profiler (a meter that records current against time) shows the AP rail leaping to 100 mA once a second. The measurement says something wakes the AP every second. The cause, in this kind of bug, is often a sensor interrupt wired to the AP instead of the hub, or a driver that polls. The fix is to move the interrupt, then repeat the measurement until the AP rail stays flat.

On real hardwareTake an STM32 Nucleo-L476RG and an LSM6DSV16X breakout on I2C. Put the MCU in Stop 2, the sensor in power-down, and read the supply current through the board’s current-measurement header (check your board’s user manual for its name). Then turn the accelerometer on at 60 Hz in low-power mode. The current should rise by about 17 µA, as the datasheet says. A difference far from that points at a floating pin or a pull-up wasting current.
A design uses the 2 mA suspend state of the main processor as its idle floor. Why can that processor not also be the always-on watcher?

Chapter 2

The Current Ledger

Count charge per second, and see why many short wake-ups cost more than one long one

Your phone says the battery lasts two days. Your friend’s identical phone, with one extra app, lasts one. The screen was off the whole time in both cases. Where did the second day go? The answer is not in how hard the processor worked. It is in how often it woke.

To see why, we need one tool: a ledger. It adds up charge, the way a bank adds up money, and it shows which wake-ups are expensive.

Current is charge per second

Current is how much electric charge flows past a point each second. Picture water in a pipe: current is litres per second. A battery is a tank. Its label, in milliamp hours (mAh), says how much charge the tank holds. A 300 mAh battery can supply 300 mA for one hour, or 1 mA for 300 hours.

A processor does not draw one steady current. It draws a lot when awake and a little when asleep. So we ask for the average current: the total charge drawn in a period, divided by the length of the period. Charge in milliamp seconds is current times time. We add one entry per state, then divide.

Iavg
The average current over the period, in milliamps. Battery life in hours is the battery’s mAh divided by this.
1 / T
One over the length of the period. Use one second and the ledger reads in milliamp seconds per second, which is just milliamps.
∑k
Add up one line for every state the processor visits in the period: asleep, resuming, working.
Ik · tk
The current in state k times the time spent there. This is the charge that state costs.

Three designs, three ledgers

Use the numbers from the hero. The big processor draws 100 mA awake and 2 mA suspended. Each wake keeps it awake for 6 ms, which covers the resume and a short read. The sensor produces 60 samples a second.

Design A: the processor polls. It never suspends. One line: 100 mA × 1 s = 100 mC. The average is 100 mA.

Design B: the sensor interrupts the processor on every sample. The processor sleeps between samples. Awake time is 60 × 6 ms = 360 ms. Asleep time is 640 ms. Line one: 100 mA × 0.36 s = 36 mC. Line two: 2 mA × 0.64 s = 1.28 mC. Total 37.28 mC in one second, so the average is 37.3 mA.

Design C: the hub decides. The processor wakes only for a gesture. Say 20 gestures an hour, 500 ms each for the screen. That is 10 s awake in 3,600 s. Awake share 0.28%. The processor line: 98 mA extra × 0.00278 = 0.272 mA above the 2 mA floor. The hub rail adds 0.054 mA. Total 2 + 0.272 + 0.054 = 2.33 mA.

Run the battery: 300 mAh divided by each average gives 3.0 hours, 8.0 hours and 129 hours. Design C wins by a factor of 43 over A and 16 over B. Try your own numbers below.

Fill the ledger

The top strip is one second of processor current. Each purple block is one wake. The yellow line is the average. Set how many wakes there are and how long each one lasts. The bars below show where the charge goes.

60
6 ms

Illustrative processor: 100 mA awake, 2 mA suspended, a 300 mAh battery. If the awake blocks would overlap in one second, the model caps the awake share at 100%.

Slide the wakes to 100 and the duration to 10 ms. The blocks fill the whole second and the average reaches 100 mA. The processor can no longer sleep. Now slide back to 2 wakes of 6 ms. The average drops to 2.2 mA. Almost all of it is the floor.

The wake tax

Look at the 6 ms. The work itself, reading seven bytes from the sensor, is a fraction of a millisecond. Most of the time goes to the resume: restoring clocks, running the interrupt, scheduling the task and letting the operating system settle. This is a fixed tax on every wake. It does not shrink when the work shrinks.

That is why the cure is fewer wakes, not faster code. Making the read twice as fast saves 0.1 ms of 6. Waking once for 60 samples instead of 60 times saves 59 resumes. Chapter 5 builds that batch.

The ledger also shows the floor. In Design C the processor floor is 2 mA, which is 86% of the total. After the hub has done its job, the next win lies in the AP’s suspend state, which the sleep and battery lesson treats.

The failure you will meet

Symptom: the spec sheet predicts five days and the device lasts two. Measurement: capture the supply current for ten minutes and zoom into one second. You see dozens of short spikes where the model predicted none. Each spike is a wake nobody asked for: a timer, a network keep-alive, a driver that polls. Fix: list the wake sources, remove or batch each one, and capture again.

On real hardwareUse an STM32 Nucleo-L476RG and any power profiler with microamp resolution. Run a loop that wakes on a 60 Hz timer and does a dummy read, then run a loop that sleeps for one second and wakes once. Capture 10 seconds of each. Compare the average with the ledger: sum current times time for every state in the capture. The two numbers should agree within a few percent.
A processor draws 100 mA awake and 2 mA asleep. It wakes 10 times a second for 10 ms each. About what is its average current?

Chapter 3

The Wake-Up Threshold

Set the first filter, which lives inside the sensor, and measure what it catches and what it lets through

A phone lies flat on a desk. A truck passes outside and the desk shivers. Ten seconds later you pick the phone up. A good design wakes for the second event and ignores the first. The sensor has to tell them apart with no help from any processor, using only a number you set once.

That number is the wake-up threshold. It is the cheapest filter in the whole system, because it runs inside the sensor on microamps. It is also the easiest to set wrong.

What the sensor reports

An accelerometer measures how hard it is pushed, in units of g (one g is the pull of Earth’s gravity). A phone lying still reads 1 g straight down, not 0. Motion shows up as a change on top of that 1 g. Small changes are quoted in milli-g (mg): 1,000 mg is 1 g. The lesson on what an IMU really measures explains bias and noise.

The sensor first removes the constant 1 g with a high-pass filter: a filter that keeps fast changes and drops slow ones. The datasheet for the ST LSM6DSV16X lets you pick a high-pass filter or a slope filter for the wake-up function. What remains is the motion. The wake-up rule asks one question of each sample: is the motion bigger than the threshold?

The threshold is a register

In the LSM6DSV16X the threshold lives in register WAKE_UP_THS at address 5Bh. Its field WK_THS has 6 bits, so it holds 0 to 63. Each step is worth a weight set in another register field. The default weight is 7.8125 mg per step. So a value of 8 means 8 × 7.8125 = 62.5 mg. The largest value at the default weight is 63 × 7.8125 = 492 mg. Other weights run up to 250 mg per step.

The TDK ICM-42670-P does the same job with three registers, one for each axis: ACCEL_WOM_X_THR, Y and Z. Each is 8 bits, and the datasheet says the resolution is 1 g divided by 256, about 3.9 mg per step. A value of 16 means 62.5 mg too.

Why do the two parts give such different steps? The ST part has a coarse 6-bit field and a choice of weights. The TDK part has a fine 8-bit field. Both are guesses at the same design question: how small a motion should wake the system?

Duration: how long above the line

A threshold alone fails on a knock. A knock is tall and short: one sample at 140 mg and then nothing. A pickup is smoother and lasts longer. So both parts add a duration: the signal must stay above the line for several samples in a row. The LSM6DSV16X field WAKE_DUR counts in units of one sample period at the accelerometer rate. The ICM-42670-P field WOM_INT_DUR picks the first, second, third or fourth over-threshold event before it raises the interrupt.

The two knobs fight different enemies. Raise the threshold and you lose weak real events. Raise the duration and you lose short real events. Try both on the same 12 seconds of motion. The model uses a 60 Hz sensor, and a real wake needs the signal above the line for n samples in a row, where n is one more than the duration field.

Tune the wake-up filter

The blue trace is motion after the high-pass filter, in mg. The teal band is your threshold. Brackets mark three real pickups, green if caught and red if missed. Grey brackets mark knocks and vibration. Each tick is a wake: green if it landed on a pickup, red if not.

8 = 62.5 mg
1 = 2 samples

Toy data, seeded so it is the same on every visit: noise of about 6 mg, three pickups (peaks 180, 230 and 150 mg), six knocks of 1 or 2 samples and two bursts of vibration. After each wake the model ignores the sensor for 0.5 s. The step size is the LSM6DSV16X default weight of 7.8125 mg.

Work the default by hand. At 62.5 mg with 2 samples, one-sample knocks vanish, because they are never above the line twice in a row. The two-sample knocks still pass. Raise the duration to 3 samples and they vanish too, but now check the weak pickup. Its peak is 150 mg and it stays above 62.5 mg for 8 samples, so it survives. Push the threshold to 25 steps (195 mg) and the weak pickups fall below the line. You trade a false wake for a missed one.

Let the sensor slow itself down

The sensor can also save current on its own. The LSM6DSV16X has an inactivity function. After a quiet spell, it drops the accelerometer to a lower rate by itself. The quiet spell is set by SLEEP_DUR, where one step is 512 sample periods, and the default of 0 means 16 periods. When motion returns, the sensor goes back to the faster rate. The hub never has to ask.

Here is the register setup for a 60 Hz wake-up on the LSM6DSV16X. The register addresses and bit names come from the datasheet. Check them against your revision before you use them.

c/* LSM6DSV16X wake-up on INT1. i2c_write(reg, value) is your bus driver. */
#define CTRL1            0x10   /* accel: OP_MODE_XL[6:4], ODR_XL[3:0] */
#define FUNCTIONS_ENABLE 0x50   /* bit 7 INTERRUPTS_ENABLE */
#define WAKE_UP_THS      0x5B   /* WK_THS[5:0], default 7.8125 mg per step */
#define WAKE_UP_DUR      0x5C   /* WAKE_DUR[6:5], 1 step = 1 / ODR_XL */
#define MD1_CFG          0x5E   /* bit 5 INT1_WU routes wake-up to INT1 */

void wake_config(void) {
    i2c_write(FUNCTIONS_ENABLE, 0x80);   /* turn the basic interrupts on */
    i2c_write(WAKE_UP_THS,      8);      /* 8 x 7.8125 mg = 62.5 mg */
    i2c_write(WAKE_UP_DUR,      1 << 5); /* WAKE_DUR = 1 */
    i2c_write(MD1_CFG,         1 << 5); /* INT1_WU */
    i2c_write(CTRL1,          0x45);    /* low-power mode 1, 60 Hz: 0x40 | 0x05 */
}

Note the order. The accelerometer starts only when CTRL1 gets a non-zero rate, so write it last. The sensor then raises INT1 on a wake-up event with no further help. The pin goes to a wake input on the hub.

The failure you will meet

Symptom: a wearable wakes its phone dozens of times a day with no one touching it. Measurement: log each wake with the time and the peak value that caused it. You find a cluster at the same hour, a washing machine or a bus. Fix: raise the duration first, since vibration is long but low, and lift the threshold only if duration alone fails. Then replay the logged motion to check that real pickups still pass.

On real hardwareUse an STM32 Nucleo-L476RG with an LSM6DSV16X breakout. Load the setup above, route INT1 to a GPIO that wakes the MCU from Stop 2, and toggle an LED in the handler. Tap the desk, then lift the board. Log the WAKE_UP_SRC register (45h) on each wake to see which axis fired. Repeat with the threshold at 4 and at 20 and note which events change.
A wearable wakes its processor for every desk knock but misses nothing it should catch. Which change fixes the knocks with the least risk to real events?

Chapter 4

Gestures as State Machines

Turn a tilt angle into a raise-to-wake event with four states, an angle and a hold time

You reach for your phone. As your hand lifts it, the screen glows before the phone is level. Now you walk with the phone swinging at your side. The screen stays dark. The sensor saw a tilt in both cases. Something remembered the difference: the first tilt stayed, the second came and went.

That something is a state machine: a small program with a few named states, and rules for moving between them. It is the standard shape for gestures in firmware, because it needs very little memory and very little arithmetic, and the hub can run it forever.

Step one: a tilt angle from gravity

A gesture starts with a number. The simplest number is the tilt: how far the device’s screen has turned from lying flat. A still accelerometer measures gravity, so it works like a compass for up. Face-up on a table, the sensor reads (0, 0, 1) g. Tilt the phone toward you and the z reading shrinks while another axis grows.

Take a reading of (0.50, 0, 0.87) g. The total strength is the square root of 0.50² + 0.87², which is 1.00 g. Tilt is the angle whose cosine is z divided by the total: cos−1(0.87) = 30°. A reading of (0.64, 0, 0.77) g gives cos−1(0.77) = 39.6°. This works only when the device is still. During a shake the sensor feels gravity plus motion, and the angle jumps around. The hold time below fixes much of that.

The hub does not need the cosine function. It can compare squares. The test “tilt is above 35°” means z is below cos 35° of the total, and cos² 35° = 0.671. So the hub checks z² × 1000 < 671 × (x² + y² + z²). Integer maths only.

Step two: four states

The TDK ICM-42670-P documents its tilt feature in one line: it issues an interrupt when the tilt angle exceeds 35 degrees for more than a programmable time. That is already a state machine with two parameters. We add a lockout so one lift gives one event.

  1. IDLE: the tilt is below the angle. Do nothing. If the tilt rises above the angle, go to ARMED and start a timer.
  2. ARMED: the tilt is above the angle. If it falls back, return to IDLE. If the timer reaches the hold time, go to FIRE.
  3. FIRE: raise the interrupt line to the AP. Go to LOCKOUT at once.
  4. LOCKOUT: ignore everything until the tilt falls below the angle again. Then return to IDLE.

The hold time turns a spike into a decision. A wobble crosses the angle for a few tens of milliseconds. A real lift stays above it. The price is latency: the screen cannot light before the hold time has passed. A 200 ms hold means the earliest wake is 200 ms after the tilt crosses the line.

Android describes three gestures a device may offer. The tilt detector fires each time a tilt is detected and is meant to let the system suspend. The pick-up gesture fires when the device is picked up, wherever it was before. The wake-up gesture acts as if the power button were pressed, turns the screen on, and, in the documentation’s words, must be low power since it is likely activated 24/7. All three are wake-up sensors: they may wake the AP from suspend.

Run the gesture machine

Pick a recorded motion. The blue line is the tilt angle. The ribbon under it is the machine: grey is IDLE, teal is ARMED, green is FIRE and LOCKOUT. Press Replay, then change the angle and the hold time.

35°
200 ms

Toy motions at 50 Hz for 3 seconds: the lift rises from 8 to 62 degrees between 0.5 and 0.9 s; the wobble has bumps of 46 and 38 degrees lasting 80 and 100 ms; the walk is 25 degrees plus or minus 17 at 1.8 Hz. The 35 degree default is the ICM-42670-P tilt angle; the rest is illustrative.

Try the walk with the default 200 ms hold. The angle is above 35° for only about 165 ms in each swing, so the machine arms and then falls back. Lower the hold to 100 ms and the screen flashes on at every step. Now try the lift. It crosses 35° at 0.72 s and fires at 0.90 s. A hold of 0 fires at about 0.74 s, and then the wobble fires too.

A fixed hold is a blunt tool. Real products also check that the device is turning toward face-up, and that it is not in a walking pattern. Those checks add states, not new ideas.

The same machine in C

c/* Tilt gesture on the hub. Called at 50 Hz with accelerometer readings in mg. */
typedef enum { IDLE, ARMED, LOCKOUT } state_t;
static state_t st = IDLE;
static uint16_t held;                          /* ticks spent above the angle */
#define TICK_MS   20
#define HOLD_MS   200
#define COS2_PM   671                         /* cos^2(35 deg) x 1000 */

static bool tilted(int32_t x, int32_t y, int32_t z) {
    int64_t m2 = (int64_t)x*x + (int64_t)y*y + (int64_t)z*z;
    return (int64_t)z*z*1000 < COS2_PM * m2;     /* tilt above 35 degrees */
}

bool gesture_step(int32_t x, int32_t y, int32_t z) {
    bool t = tilted(x, y, z);
    switch (st) {
    case IDLE:    if (t) { st = ARMED; held = 0; } break;
    case ARMED:   if (!t) { st = IDLE; break; }
                  if (++held * TICK_MS >= HOLD_MS) { st = LOCKOUT; return true; }  /* FIRE */
                  break;
    case LOCKOUT: if (!t) st = IDLE; break;
    }
    return false;
}

The function returns true once per gesture. The caller pulls a GPIO line high, and the AP wakes. FIRE needs no state of its own here because the function returns during the transition.

The failure you will meet

Symptom: the screen lights while the owner walks, one flash per stride. Measurement: log the angle and the machine state at 50 Hz during a walk, then plot them as above. The angle crosses the line on every swing, and the hold is shorter than the time spent above it. Fix: lengthen the hold, then add a rule that blocks the gesture while a walking pattern is active. Verify with the logged walk and with ten real lifts.

On real hardwareOn an STM32 Nucleo-L476RG with an LSM6DSV16X, run gesture_step from a 50 Hz timer. Print a line with the time, the squared test result and the state over the debug port. Record one raise, one desk bump and a 30 second walk, and replay the file through the device above or a script. Check the fire times against the table in the text.
A raise-to-wake gesture uses a 35 degree angle and a 200 ms hold. The user lifts the phone and the tilt crosses 35 degrees at t = 0.60 s. When is the earliest the machine can fire?

Chapter 5

Batching to the Application Processor

Size the FIFO watermark so the processor wakes rarely, loses nothing, and still gets the data in time

The hub now knows how to wake the AP for a gesture. But some apps want the raw motion too: a step counter, a sleep tracker, a map that follows you indoors. They need hundreds of samples a second. If the AP woke for every sample, Chapter 2 tells us what would happen. The cure is to collect samples in a queue and hand them over in a lump.

The queue, the line and the bell

A FIFO (first in, first out) is a queue in hardware. Think of a conveyor belt at a till. The sensor puts samples on one end. Whoever reads takes them off the other end, oldest first. The lesson on FIFO, watermark and timestamps builds this in detail. Here is the short version.

The watermark is a line painted on the belt. When the queue grows past the line, the sensor rings a bell: it raises an interrupt pin. The reader then takes everything off in one go. In the ST LSM6DSV16X the line is the field WTM in register FIFO_CTRL1 at 07h. The bell is the flag FIFO_WTM_IA, routed to a pin with INT1_FIFO_TH in INT1_CTRL at 0Dh. Each FIFO word is 7 bytes: one tag byte that names the sensor, and 6 bytes of data for x, y and z. The count of unread words sits in FIFO_STATUS1 and FIFO_STATUS2.

Capacity matters. The datasheet says the part holds 1.5 KB, which is 1,536 ÷ 7 = 219 words, and up to 4.5 KB when you switch on compression. The TDK ICM-42670-P holds up to 2.25 KB, and shares its memory with the APEX features, so the default FIFO is 1 KB.

Three numbers you control

Let the sensor run at f samples a second. Let the watermark be W words. Three results follow at once.

First, the bell rings f / W times a second. At 240 Hz with W = 10, that is 24 interrupts a second instead of 240. The Android documentation uses this very example: a 240 Hz gyroscope batched 10 at a time cuts the interrupts from 240 to 24 a second.

Second, the oldest sample in a batch has waited W / f seconds. At W = 10 and 240 Hz that is 41.7 ms. Android calls the longest wait you allow max_report_latency. A value of zero means report each event as soon as it is measured. The documentation suggests about 3 seconds for gesture recognition at 50 Hz and 1 to 10 minutes for walking-path tracking. Timestamps still show when each event really happened, not when it arrived.

Third, the queue has room for only so many words. If the AP takes too long to answer the bell, the queue fills and loses data. The grace time is the number of free words divided by the sample rate. With a 219-word FIFO and W = 100, the grace time at 240 Hz is (219 − 100) / 240 = 0.50 s.

The price of a read

A batch is not free to read. At a 400 kHz I2C clock, each byte takes 9 clock pulses (8 data bits and an acknowledge). A 7-byte word takes 63 pulses, or 157.5 µs. Reading W words takes about 0.1575 × W ms. Add the 3 ms resume tax from Chapter 2. For W = 10, the AP is awake 3 + 1.6 = 4.6 ms per interrupt. For W = 120 it is 3 + 18.9 = 21.9 ms.

Now the average current at 240 Hz. W = 1: 240 wakes of 3.2 ms is 76% awake, and about 76 mA. W = 10: 24 wakes of 4.6 ms is 11% awake, and 12.8 mA. W = 120: 2 wakes of 21.9 ms is 4.4% awake, and 6.3 mA. W = 219: 1.1 wakes of 37.5 ms, and 6.0 mA. The curve flattens. The resume tax is gone, but the cost of moving the bytes stays.

Size the batch

Yellow: interrupts per second. Blue: the wait of the oldest sample. Purple: average processor current. The red zone is where the FIFO overflows for the delay you set. The strip at the bottom shows 250 ms of samples and bells.

10 words
20 ms

FIFO size from the LSM6DSV16X datasheet: 1.5 KB uncompressed, 7 bytes a word, so 219 words. The read time assumes 400 kHz I2C and no address overhead. The 3 ms resume, the 100 mA and 2 mA of the processor and the answer delay are illustrative.

Set 240 Hz and drag the watermark to 1. The strip fills with bells and the current climbs past 70 mA. Drag it to 219 and the current settles near 6 mA, but the latency passes 0.9 s. Now raise the answer delay to 500 ms. The red zone grows from the right and now covers every watermark above 99 words. A slow AP forces a small watermark.

Choosing the watermark

Work from the constraint that bites first. Ask the app how stale its data may be: that caps W / f. Ask how slow the AP can be in the worst case, such as a garbage-collection pause or a busy bus: that caps W through the grace time. Take the smaller W. Then check the current. If it is too high, the answer is not a bigger W but less data: lower the rate, compress, or process on the hub.

Here is the register setup for 240 Hz accelerometer batching with the bell on INT1. As before, check the names against your datasheet revision.

c/* LSM6DSV16X: batch the accelerometer at 240 Hz, bell every 10 words. */
#define FIFO_CTRL1  0x07   /* WTM[7:0], low bits of the watermark */
#define FIFO_CTRL3  0x09   /* BDR_GY[7:4], BDR_XL[3:0]; 0111 = 240 Hz */
#define FIFO_CTRL4  0x0A   /* FIFO_MODE[2:0]; 110 = continuous */
#define INT1_CTRL   0x0D   /* bit 3 INT1_FIFO_TH */
#define CTRL1       0x10
#define FIFO_ST1    0x1B   /* DIFF_FIFO[7:0]; DIFF_FIFO[8] is in FIFO_STATUS2 (1Ch) */
#define FIFO_TAG    0x78   /* then 6 data bytes at 79h to 7Eh */

void batch_config(void) {
    i2c_write(FIFO_CTRL1, 10);          /* watermark W = 10 words */
    i2c_write(FIFO_CTRL3, 0x07);        /* accelerometer into FIFO at 240 Hz */
    i2c_write(FIFO_CTRL4, 0x06);        /* continuous: the newest sample overwrites the oldest */
    i2c_write(INT1_CTRL,  1 << 3);   /* bell on INT1 */
    i2c_write(CTRL1,      0x47);        /* low-power mode 1, 240 Hz */
}

int drain(uint8_t (*out)[7], int max) {      /* call from the thread the bell wakes */
    int n = i2c_read8(FIFO_ST1);                /* low 8 bits of the count; fine while W < 256 */
    if (n > max) n = max;
    for (int i = 0; i < n; i++) i2c_read_burst(FIFO_TAG, out[i], 7);
    return n;
}

Each word carries a tag, so the reader can tell accelerometer words from gyroscope or timestamp words. With IF_INC set, the register address steps forward on its own, so one burst of 7 bytes reads the whole word.

The failure you will meet

Symptom: the step counter loses a few percent of its steps, but only when the phone is busy. Measurement: read the sensor’s FIFO overrun flag, and compare the count of words received per minute with the expected rate times 60. You see gaps that line up with CPU load. Fix: lower the watermark so the grace time exceeds the worst answer delay, and in the long run give the interrupt a higher priority than the work that delays it.

On real hardwareOn an STM32 Nucleo-L476RG with an LSM6DSV16X, set the 240 Hz batch above. Count bell edges for 10 seconds on a GPIO input: with W = 10 you should see about 240. Now busy-wait for 600 ms in the handler on purpose. Read FIFO_STATUS2: the overrun flag should set, and the sample counter should show a gap.
A sensor runs at 240 Hz with a watermark of 10 words. How many interrupts a second does it raise, and how long can the oldest sample wait?

Chapter 6

Two FIFOs and a Sleeping Processor

Choose between a queue that may wake the AP and a queue that must stay silent, and count what each one loses

A sleep tracker runs all night. The phone lies on the bedside table, suspended. The tracker wants every motion sample, but only needs them by morning. Which design lets it have them? One design hands over the whole night. The other hands over the last four seconds. Both batch correctly. They differ in one flag.

Two kinds of event

The Android sensors documentation sorts every sensor event into two kinds. A wake-up event may wake the AP from suspend. A non-wake-up event must never wake it. The sensor hub keeps them in separate queues. The documentation says explicitly that the two cannot be interleaved in the same FIFO.

The rules differ at the one point that matters: what happens when the queue is full while the AP sleeps.

A non-wake-up FIFO must wrap around and behave like a circular buffer. The newest sample overwrites the oldest. The AP stays asleep. In the documentation’s words, max_report_latency has no effect on it while the AP is suspended. Nothing is lost that the app can still ask for, but the history is only as long as the queue.

A wake-up FIFO works the other way. When it fills, or when its latency runs out, the hardware wakes the AP and reports the data. Nothing is lost, and the AP pays a wake for each batch.

There is a third rule that glues them together. When the AP comes out of suspend for any reason, a batch is produced at once with the content of all FIFOs. So one wake-up event, such as the user pressing the power button, flushes the silent queue too.

How the hub decides to ring the bell

The Bosch BHI260AP datasheet lists, in order, the cases where its host interrupt pin goes active. Four are worth knowing. A sensor with zero max report latency has produced a sample. A sensor with a non-zero latency has timed out. The watermark has been exceeded before the latencies ran out. And two cases for a suspended AP: if wake-up sensors are enabled and a wake-up event happens, the pin goes active, and no other event except an unexpected reset will raise the pin in that state. If the wake-up FIFO has a non-zero watermark and every enabled sensor has non-zero latency, the AP wakes when the watermark is reached.

That list is a decision table the hub firmware must implement. Each row is a few lines of code, and each is a place for a bug.

The sleep tracker, in numbers

Take the part from Chapter 5: 219 words and 60 Hz. The queue fills in 219 ÷ 60 = 3.65 s. Watch 40 seconds, and ask what the AP receives. That is 40 × 60 = 2,400 samples.

Non-wake FIFO, nothing else happens: the AP sleeps all 40 s and then you press the power button. It receives 219 samples, the last 3.65 s. The other 2,181 were overwritten.

Add one wake-up event at 22 s, such as the significant motion detector. Android lists this sensor as wake-up only. The AP wakes at 22 s and receives the 219 words queued so far. Then it sleeps again. At 40 s it receives another 219. Total received: 438. Lost: 1,962.

Wake-up FIFO with a 20 s latency limit: the queue fills every 3.65 s, so the latency never matters. The AP wakes 11 times in 40 s. It receives all 2,400 samples. The AP pays 11 wakes of about 37 ms: roughly 1 mA extra on top of its 2 mA floor. If the FIFO were bigger than 20 s of data, the latency limit would set the wake rate instead.

Fill the queue while the AP sleeps

The line is how full the FIFO is. Choose its kind, then toggle the significant-motion event at 22 s and move the latency limit. Purple ticks are moments the AP wakes. The red area is data overwritten before anyone read it.

20 s

Model: 60 Hz, 219-word FIFO, the AP suspended from 0 to 40 s, and a power-button press at 40 s that flushes everything. A wake costs 3 ms plus 0.1575 ms a word on a 100 mA processor. The processor figures are illustrative.

Slide the latency to 2 s with the wake-up FIFO. The AP now wakes 21 times, because the latency limit now forces a wake before the queue fills. Each one flushes a smaller batch, so the resume tax returns. The latency limit is a dial between freshness and current, just as the watermark was in Chapter 5.

Which kind for which job

Ask what the app does if a sample is lost. A step counter that must be right by morning needs a wake-up FIFO, or hub-side counting, because the history cannot be rebuilt. A screen-on gesture is a wake-up event by nature. A display-rotation sensor needs fresh data only while the screen is on, so a silent queue is enough. The step detector is listed by Android as non-wake-up. It is the hub’s job to keep counting steps, and let the AP read the count when it next wakes.

The failure you will meet

Symptom: a sleep graph has a clean last few seconds before you woke, and nothing before. Measurement: log the timestamp of the oldest sample in each delivered batch. In the morning it is only seconds old, never hours. Fix: register the sensor with a wake-up FIFO and a latency of minutes, or move the counting into the hub so it stores a few bytes a minute and not thousands of samples.

On real hardwareOn an STM32 Nucleo-L476RG with an LSM6DSV16X, set FIFO_MODE to continuous (110) with the accelerometer at 60 Hz and put the MCU in Stop 2. After 10 seconds, wake it and read DIFF_FIFO. It should equal the FIFO depth, 219 words, and the overrun flag should be set. Enable the sensor timestamp and check that the oldest word is about 3.65 s old.
An app registers a sensor on a non-wake-up FIFO with a max report latency of 10 minutes. The AP stays suspended for 10 minutes. What does the app receive when the AP wakes?

Chapter 7

The Hub’s Own Firmware

Write the loop that sleeps between events, and budget the cycles each sample is allowed to cost

Picture the hub as a night watchman with one job. He sits in a chair. When a bell rings he stands, checks one thing, and sits back down. He never patrols. Firmware for an always-on chip has this shape: most of its life is the chair.

This chapter writes that firmware and counts its cost. The central idea is simple. The hub should do the least work per sample it can, and spend every other microsecond asleep.

Events, not loops

A beginner’s program is a loop that keeps asking “is there new data?”. That is polling, and it keeps the chip in run mode. The better shape reacts to events. An interrupt is a hardware tap on the shoulder: a pin changes, and the processor stops what it is doing and runs a short function called the interrupt service routine (ISR).

Keep the ISR tiny. It clears the hardware flag, sets a bit in a variable, and returns. The real work happens back in the main loop. This keeps the chip’s response time short and its code easy to reason about. The lesson on embedded real-time systems goes deeper into priorities.

Between events the chip executes WFI, the Arm instruction “wait for interrupt”. The core stops its clock until some interrupt arrives. On an STM32L476, you set a bit in the System Control Register first to choose deep sleep, and the vendor library offers a routine that enters Stop 2 (see the reference manual for your part). After a Stop wake-up, the clock tree may restart from a slow internal oscillator, so the code re-selects the clock it wants.

The race you must not lose

A subtle bug sits in the simplest loop. The code checks the flag, finds it clear, and is about to execute WFI. At that instant the interrupt fires, sets the flag, and returns. Now the code runs WFI and sleeps with a flag waiting. This is a lost wake-up.

The cure is to mask interrupts around the check. On Cortex-M the PRIMASK register blocks interrupt handlers. The Arm architecture says WFI ignores PRIMASK when it asks whether an interrupt should wake the core. So an interrupt that arrives while PRIMASK is set stays pending, wakes the WFI at once, and runs when you unmask. The pattern is below. Arm Community threads quoting the ARMv7-M Architecture Reference Manual describe the rule, and you should read the reference manual for your part.

c/* The hub's main loop for an STM32L476 (Cortex-M4). */
enum { EV_FIFO = 1 << 0, EV_WAKEUP = 1 << 1, EV_AP_CMD = 1 << 2 };
static volatile uint32_t events;

void EXTI9_5_IRQHandler(void) {                  /* sensor INT1 on pin 7 */
    if (EXTI->PR1 & (1u << 7)) {
        EXTI->PR1 = (1u << 7);                /* write 1 to clear the pending bit */
        events |= EV_FIFO;                     /* say what happened, nothing more */
    }
}

int main(void) {
    hub_init();                                  /* clocks, I2C, sensor setup from Chapters 3 to 5 */
    for (;;) {
        __disable_irq();                         /* mask, but WFI still wakes on a pending interrupt */
        uint32_t e = events; events = 0;
        if (!e) { __DSB(); enter_stop2(); }          /* sleep until the next bell */
        __enable_irq();                          /* a pending ISR runs now */
        if (e & EV_FIFO)   drain_and_process();      /* the fewest cycles possible */
        if (e & EV_WAKEUP) raise_ap_line();
    }
}

Each pass through the loop does one of two things. It sleeps, or it handles the events it found. Nothing spins.

The cycle budget

Now the cost. The datasheet gives the STM32L476 100 µA per MHz in run mode. Read that as a price per cycle: 100 µA divided by one million cycles a second is 100 picocoulombs of charge per cycle. It is the same at any clock speed, to first order. A job of 6,000 cycles costs 6,000 × 100 pC = 0.6 µC, whether it runs at 4 MHz or 48 MHz.

At 60 samples a second the job runs 60 times: 36 µA of average compute current. The hub is busy 6,000 ÷ 16 MHz = 0.375 ms per sample, which is 2.25% of the time at 16 MHz. The rest it spends in Stop 2 at 1.1 µA. Add the sensor’s 17 µA at 60 Hz in low-power mode. The total is 36 + 1.1 + 17 = 54 µA.

So the lever is cycles per sample. Halve the cycles and the compute current halves. A faster clock does not change the charge, but it shortens the busy time, which matters for response and for hitting the next sample on time. A slower clock saves nothing and risks overrun: if the work takes longer than the sample period, the hub never sleeps and falls behind.

Budget the hub’s cycles

The bar splits the hub rail into compute (warm), sleep (grey) and the sensor (blue). The strip shows two sample periods: the warm block is the hub running, the rest is Stop 2. Set the work per sample, the sample rate and the clock.

6,000
60 Hz

Datasheet values: 100 µA/MHz run and 1.1 µA Stop 2 (STM32L476), accelerometer 4.0 µA at 1.875 Hz and 17 µA at 60 Hz in low-power mode 1 (LSM6DSV16X). The sensor current at 15 and 30 Hz is a straight line between those two points, and wake-up time from Stop is ignored. Both are model choices.

Set 6,000 cycles at 60 Hz and 16 MHz, then switch to 80 MHz. The busy block shrinks fivefold and the compute current barely moves. Now push the work to 100,000 cycles at 4 MHz. The block is longer than the period. That is an overrun, and the hub misses samples.

Modes as states

A real hub also has modes, and they are a state machine one level up from Chapter 4. A wearable might use three. In standby, the sensor runs its own wake-up function at a low rate, and the hub sleeps in Stop 2. In assist, the hub reads the sensor at 60 Hz and runs gesture rules. In continuous, the hub batches data at a higher rate for the AP. These names are our example. A transition costs a few register writes, so the hub should move up only on demand, and fall back to standby after a quiet spell.

The failure you will meet

Symptom: the step count drifts low on a busy day, and the hub rail current is higher than the model. Measurement: toggle a spare pin high at the start of the work and low at the end, then capture the pin on a logic analyzer with the current. The pulse is longer than expected and sometimes still high when the next bell rings. Fix: move code out of the ISR, shrink the work, or lower the rate. Measure cycles directly with the Cortex-M4 DWT cycle counter before you trust any estimate.

On real hardwareOn an STM32 Nucleo-L476RG, enable the DWT cycle counter (CYCCNT) and wrap drain_and_process with two reads. Print the worst case over 1,000 calls. Multiply by the sample rate and 100 pC to predict the compute current, then measure the board with a power profiler and compare. Expect to find the wake-up overhead you left out of the model.
A hub job takes 6,000 cycles per sample at 60 Hz on a part that costs 100 µA per MHz. A designer moves from 16 MHz to 48 MHz. What changes?

Chapter 8

Sensors That Classify

Move “still, walking or running?” into the sensor with a small decision tree, and see what it costs in accuracy and delay

A fitness band wants to know what you are doing: sitting, walking or running. It could send raw motion to the hub at 60 samples a second and let the hub work it out. Or the sensor could do the working out itself and send one word when the answer changes. The second design moves less data and wakes the hub less often.

Some sensors can do this. The ST LSM6DSV16X includes a dedicated block, the machine learning core (MLC). Its datasheet describes it as a way to move algorithms that run on the application processor into the sensor, for a consistent reduction in power. This chapter builds the idea from zero.

Step one: features from a window

Raw samples are too many and too noisy to judge one by one. So we cut the stream into windows, short slices of time such as 2 seconds, and boil each window down to a few numbers called features. Two features carry a lot of motion information.

The first is the standard deviation: how widely the readings spread around their average. It measures how vigorous the motion is. Work it for six readings of motion, in mg: −30, 40, −10, 50, −40, 20. The sum is 30, so the mean is 5. The gaps from the mean are −35, 35, −15, 45, −45, 15. Their squares are 1225, 1225, 225, 2025, 2025, 225, which add to 6950. Divide by 6: 1158. The square root is 34 mg.

The second is the crossing rate: how many times a second the signal crosses its own average. It estimates the rhythm. Steps come about twice a second when you walk, and about three times when you run. The datasheet’s computation block offers filters and features over a window you define, and the features can be read back through the FIFO.

Step two: a tree of questions

A decision tree is the game of twenty questions as a program. Each question compares one feature with a threshold. Each answer leads to another question, or to a final label. Here is a tree for four activities:

  1. Question 1: is the standard deviation below T1? If yes, the device is quiet or in a vehicle. Go to question 2. If no, go to question 3.
  2. Question 2: is the standard deviation below T0? If yes, still. If no, driving, because engine vibration is small but not zero.
  3. Question 3: is the crossing rate below T2? If yes, walking. If no, running.

The datasheet describes the real thing the same way. The core works through a series of configurable nodes of “if-then-else” conditions, where feature values are checked against thresholds. It can run up to 4 decision trees at once, each with up to 16 results, and up to 128 nodes in total. The result sits in an output register that the host can read at any time. The core can raise an interrupt when the result changes.

You do not write the thresholds by hand. You record labelled motion, train a tree off-line, and load its description into the sensor. In the device below you play the trainer.

Train the tree by hand

Each dot is a 2 second window. Position is its standard deviation (across, log scale) and crossing rate (up). The shape says the true activity. The shaded region is what your tree calls it. A red ring marks a wrong call. Move the three thresholds.

20 mg
112 mg
2.4 Hz

Toy data, seeded: 10 windows per activity drawn around illustrative centres (still 8 mg, driving 45 mg and 7 Hz, walking 220 mg and 1.9 Hz, running 600 mg and 2.9 Hz). A shorter window blurs the features, so the dots spread by 2 divided by the square root of the window length in seconds, relative to a 4 second window. Node limits are from the LSM6DSV16X datasheet.

Try the 1 second window. The clusters smear into each other, and no choice of thresholds gets every window right. Switch to 4 seconds and the clusters tighten. But the sensor now answers only once every 4 seconds, and a run that lasts 3 seconds is never seen. A window is a trade between certainty and delay.

Count the cost of this tree. It uses 3 nodes out of 128. The data saved is large. Raw motion at 60 Hz with three axes of 2 bytes is 360 bytes a second. The class result is one byte, and only when it changes.

Machines that reconfigure themselves

The LSM6DSV16X also has up to 8 finite state machine programs, the gesture machines of Chapter 4 running inside the sensor. Its adaptive self-configuration lets such a machine, or a decision tree result, change the sensor’s own settings with no host involved. For example, when the tree says “still” the sensor can drop its own rate, and when it says “running” it can raise it. The hub sleeps through it all.

The failure you will meet

Symptom: a runner on a treadmill is reported as walking, and a rider on a train as still. Measurement: save every window’s features with the true label from a diary, then count the confusions. You find the treadmill runner has a smooth rhythm at 2.3 Hz, below your T2. Fix: train on more people and more places, add a feature such as peak height, and keep the tree small. Where a cheap tree cannot decide, let it wake the hub, and let the hub ask the AP’s bigger model.

On real hardwareLog 2 second windows of accelerometer data from an LSM6DSV16X on a Nucleo while you sit, walk and run. Compute the standard deviation and crossing rate in Python and plot them. Train a scikit-learn DecisionTreeClassifier with a small max_leaf_nodes. Count its nodes against the sensor’s 128, and compare its accuracy with the tree you set by hand above.
A tree classifies 2 second windows of motion. A designer switches to 4 second windows and accuracy improves. What is the price?

Chapter 9

When the Hub and the AP Disagree

Stamp samples where they are born, convert between two clocks, and detect the gaps that two sleeping chips create

A walking app draws your path on a map. In a quiet hour it looks perfect. When the phone is busy, the line jerks sideways and back. The sensors were fine. The samples arrived in lumps, and the app stamped each lump with the time it arrived. Every sample in the lump got nearly the same time, though they were taken over a tenth of a second.

Two chips mean two clocks and two schedules. Most bugs in a hub design are not in the maths. They sit at the seam between the chips. This chapter walks the three seams: time, lost data and sleep.

Seam one: whose clock?

Every chip counts time with a crystal, a tiny quartz part that rings at a fixed rate. No crystal is exact. Its error is quoted in parts per million (ppm). A 40 ppm crystal gains or loses 40 microseconds every second. Over an hour that is 40 × 10−6 × 3,600 = 0.144 s. Two chips with two crystals drift apart.

There are two ways to put a time on a sample. You can stamp it when it arrives, on the AP’s clock. Or you can stamp it where it was born, on the sensor or hub clock, and convert later. Android’s documentation is clear on the target: event timestamps reflect when the event physically occurred, not when it was reported.

Arrival stamps are wrong by up to the batch delay. With a watermark of W words at f samples a second, the oldest sample in a batch waits W ÷ f seconds, and the error grows with it. Born stamps are right at birth but live on the wrong clock. You need a map from hub time to AP time.

The clock map: offset and skew

The map has two numbers. Offset is how far apart the clocks read at one instant. Skew is how fast the gap grows. You measure both with sync pairs: read both clocks at nearly the same moment, and note the two readings.

Work an example. Pair one: hub 1000.000 s, AP 5000.012 s. Pair two, one minute later: hub 1060.000 s, AP 5060.015 s. The hub clock advanced 60.000 s. The AP clock advanced 60.003 s. The skew is 0.003 ÷ 60 = 50 ppm. To convert a hub time t to AP time, use AP = 5000.012 + (t − 1000.000) × 1.00005. The lesson on syncing many MCUs builds the filter that does this with noisy pairs.

If you never resync, the error grows by the skew every second. After 10 minutes at 50 ppm it is 30 ms. Resync once a minute and it never exceeds 3 ms. That is the trade you set below.

Compare two ways to stamp

The log-scale lines show timestamp error in milliseconds over two minutes. The yellow band is the error of stamping on arrival: anything from zero up to the batch delay. The warm line is the error of stamping at the sensor, which grows with clock drift and resets at each resync.

10 words
50 ppm

Model: 60 Hz samples. Arrival stamping errs by the time from sample to read (zero to W divided by 60 seconds). Sensor stamping errs by the skew times the time since the last sync pair, and ignores the noise of each pair. The ppm values are illustrative, typical of crystals.

Choose “Never” with 100 ppm. The warm line climbs to 12 ms in two minutes and keeps climbing. Choose “Every 1 s” and it stays at or below 0.1 ms, but now the two chips talk every second, which costs wake-ups. Pick the lowest rate whose error your app can bear.

Seam two: gaps you cannot see

Queues overflow. The Bosch BHI260AP datasheet says what its firmware does: it discards the oldest data first, in whole FIFO blocks. It then inserts an Overflow meta event at the point of loss, followed by a Full Timestamp for the first sample after the gap. The host can therefore see that data was lost, and when.

That design is the model to copy. A hub that drops data silently gives the AP a smooth-looking stream with a hole in it. A filter fed that stream cannot tell, and integrates across the hole. Always mark a gap with a flag and a fresh absolute time.

Timestamps also have a width. The LSM6DSV16X counts in 32 bits with a step of 21.75 µs, so it wraps after 232 × 21.75 µs = 93,415 s, about 26 hours. The BHI260AP uses 40 bits at 1/64,000 s and wraps after about 198 days. It also saves FIFO space by sending one full timestamp and then 8-bit or 16-bit steps, and by sharing one stamp between events with the same time. A reader must handle the wrap, or a device that runs for a day will jump back in time.

Seam three: the sleep handshake

The AP and the hub must agree on who is asleep. The BHI260AP gives the AP a bit, AP Suspend, in its Host Interface Control register. Before suspending, the AP sets it, so that only wake-up sensors raise the interrupt. The datasheet recommends flushing and emptying the FIFO first, so the AP is not woken at once by mistake. On wake, the AP clears the bit and the chip raises the interrupt if data is waiting.

If the AP skips this and only masks the interrupt line, it may wake to find the line already asserted. The first transfer is then smaller than the total available. The next transfer gets the rest. A driver that assumes one transfer per interrupt reads half the data.

The failure you will meet

Symptom: the orientation estimate lags during bursts and snaps back. Measurement: record the arrival time and the sensor time of each sample, and plot their difference. A sawtooth with the period of the batch means the AP is using arrival time. Fix: use sensor time in the filter, convert with the clock map, and check for gap markers before every batch.

On real hardwareOn an STM32 Nucleo-L476RG with an LSM6DSV16X, set FUNCTIONS_ENABLE.TIMESTAMP_EN and batch timestamps into the FIFO. At each batch, also read the MCU’s own cycle counter. Over ten minutes, plot the sensor time against the MCU time. The slope of the line minus one is the skew, in ppm. Compare it with the figure the model above predicts for a crystal.
Two clocks read 60.000 s apart on the hub and 60.003 s apart on the AP over the same minute. What is the skew?

Chapter 10

Field Guide

Keep the numbers, the checklist, the core code and the sources in one place, then go back and play with the hero

You can now say why a device carries two processors, work out the average current of a design on paper, set a wake-up filter and name its price, write a gesture as a state machine, size a batch, pick the right kind of FIFO, budget the hub’s cycles, and keep two clocks honest. Everything here is a model you can repeat on a board.

The one-paragraph summary

A sensor hub is a role: stay awake cheaply, decide, and wake the application processor only for events that matter. It saves power because the big processor costs about 2 mA even asleep and 100 mA awake in our model, while the always-on rail costs tens of microamps. The sensor filters first with a threshold and a duration. The hub runs gesture state machines and sleeps between events. Raw data crosses to the AP in batches sized by a watermark, held in a wake-up or a non-wake-up FIFO. Samples carry their own timestamps, and every gap is marked.

The numbers and terms

WhatNumberWhy it matters, and where it comes from
STM32L476 run, Stop 2, Standby100 µA/MHz; 1.1 µA; 120 nAA hub rests a thousand times below its working current. STM32L476 datasheet.
LSM6DSV16X accelerometer17 µA at 60 Hz; 4.0 µA at 1.875 Hz (low-power mode 1)The sensor is part of the always-on bill. Datasheet DS13510 Rev 3, Table 4.
ICM-42670-P sleep and six-axis3.5 µA; 0.55 mAFixed APEX functions run at the low figure. Datasheet DS-000451 Rev 1.2.
BHI260AP core950 µA at 20 MHz; 2.8 mA at 50 MHz; 7.3 µA deep sleepA programmable core inside the sensor. Datasheet BST-BHI260AP-DS000-02.
Wake-up threshold, STWK_THS 6 bits × 7.8125 mg (default); up to 492 mgThe first filter. Register WAKE_UP_THS (5Bh).
Wake on motion, TDK8 bits per axis, 1 g / 256 = 3.9 mgFiner steps, three registers. ACCEL_WOM_X/Y/Z_THR.
Tilt, TDK35 degrees for a programmable timeAngle plus hold is a gesture machine.
FIFO word and size, ST7 bytes; 1.5 KB = 219 words; up to 4.5 KB compressedSets the grace time. Datasheet section 6.12.
Batching example, Android240 Hz gyroscope, 10 per batch: 240 to 24 interrupts a secondInterrupts equal rate divided by batch. Android sensors documentation.
Machine learning core, ST4 trees, 16 results each, 128 nodes; 8 state machinesWhat fits in the sensor. Datasheet DS13510.
TimestampsST 32 bits, 21.75 µs, wraps in 26 h; Bosch 40 bits, 1/64,000 s, wraps in 198 daysHandle the wrap. Both datasheets.
Our model (illustrative)AP 100 mA awake, 2 mA suspended, 6 ms per wakeNot from a datasheet. Replace with your own measurement.

Terms in one line each. Application processor: the large, hungry chip. Sensor hub: the small chip that stays awake. Wake-up event: one allowed to wake the AP. Watermark: the FIFO level that rings the bell. Max report latency: the longest an event may wait. Skew: how fast two clocks drift apart.

The checklist

The core as code

This is the hub in one piece: three modes, the register setup for each from Chapters 3 to 5, and the loop from Chapter 7. It is a sketch that assumes the helper functions from the earlier chapters.

ctypedef enum { STANDBY, ASSIST, CONTINUOUS } hub_mode_t;
static hub_mode_t mode = STANDBY;

static void set_mode(hub_mode_t m) {
    mode = m;
    switch (m) {
    case STANDBY:                                 /* the sensor watches; the hub sleeps in Stop 2 */
        i2c_write(FIFO_CTRL4, 0x00);               /* bypass: no FIFO */
        i2c_write(WAKE_UP_THS, 8);                /* 62.5 mg */
        i2c_write(MD1_CFG, 1 << 5);           /* INT1_WU */
        i2c_write(CTRL1, 0x43);                  /* low-power mode 1, 15 Hz */
        break;
    case ASSIST:                                  /* the hub runs the gesture machine at 60 Hz */
        i2c_write(INT1_CTRL, 1 << 0);          /* INT1_DRDY_XL, one bell per sample */
        i2c_write(CTRL1, 0x45);                  /* 60 Hz */
        break;
    case CONTINUOUS:                              /* batch for the AP at 240 Hz */
        i2c_write(FIFO_CTRL1, 10);                /* watermark */
        i2c_write(FIFO_CTRL3, 0x07);              /* accelerometer, 240 Hz */
        i2c_write(FIFO_CTRL4, 0x06);              /* continuous */
        i2c_write(INT1_CTRL, 1 << 3);          /* INT1_FIFO_TH */
        i2c_write(CTRL1, 0x47);
        break;
    }
}

void hub_loop(void) {
    for (;;) {
        __disable_irq(); uint32_t e = events; events = 0;
        if (!e) { __DSB(); enter_stop2(); }
        __enable_irq();
        if ((e & EV_WAKEUP) && mode == STANDBY)  set_mode(ASSIST);
        if ((e & EV_FIFO)   && mode == ASSIST)   if (gesture_from_sample()) raise_ap_line();
        if ((e & EV_FIFO)   && mode == CONTINUOUS) drain_and_stamp();   /* flag gaps, add sensor time */
        if (e & EV_AP_CMD) apply_ap_command();                   /* the AP asks for CONTINUOUS or STANDBY */
        if (quiet_for_ms(30000)) set_mode(STANDBY);                 /* fall back after a quiet spell */
    }
}

Where this sits

This lesson follows FIFO, watermark and timestamps, which built the queue and its clocks, and sleep and the battery budget, which built the ledger. It leads into calibrating on the chip and orientation filters on an MCU, where the hub does real maths on the stream it now guards.

Keep going

Sources and credit

Built from primary sources opened for this lesson. Where we computed a number from a datasheet value, the working is in the chapter. Toy numbers are labelled illustrative.

This lesson is original. No course slides were used. The always-on idea, the tilt state machine and the model numbers are ours.

The takeaway. Do not make the big processor watch. Put the watching in the cheapest part that can do it, give it one filter at each level, and let raw data cross in batches that carry their own birth times. The saving is not in clever code. It is in how rarely the big chip wakes.
A wearable needs to light its screen on a wrist raise, count steps all night, and deliver raw motion to an app by morning. Which design fits the lesson?

Now press Present or Teach and explain, out loud and from memory, why a device carries a second tiny computer. Then go back to the hero, choose “Hub decides” and drag the gestures per hour to 200. Read how much of the battery saving survives.

The Sensor Hub: Firmware from Zero to Expertise, lesson FW-IMU-03
Sources · FIFO, watermark and timestamps · Sleep and the battery budget · Back to the Gleams