A robot joint must land where you tell it. An encoder reports the angle, and three nested loops turn that report into motor current. Switch the tuning and watch a 1 rad move ring, settle or chatter.
Learn how an encoder reports an angle, how firmware counts it, and how a position loop, a velocity loop and a current loop nest and get tuned on a joint with a loose gear.
Pick a tuning, then press Send the move. Open the gap in the gear and send it again. Then we build, piece by piece, everything underneath: the two wires that count turns, the frames that give absolute angle, the velocity estimate, and each loop in turn.
You need a little C and the idea of a feedback loop (measure, compare to the goal, push the other way). We build the rest from zero.
Part of the Firmware from Zero to Expertise series, motion control track. Built from primary sources: ST and Nordic timer and decoder manuals, the BiSS and SSI interface descriptions, and the ODrive control and tuning docs. The full source list is in the Field Guide. It follows Motors for Firmware People.
A model, not real silicon: a motor of unit inertia joined through a loose gear to a load 1.5 times as heavy, a 2,048-count-per-turn encoder on the motor shaft, and a 1 kHz control loop. The numbers are illustrative. The 1 rad step is a 0.15 s ramp. The model is written out in Chapter 9.
Chapter 0
See why a motor that only obeys commands drifts away from the truth, and what one small sensor changes
Picture the elbow of a robot arm. You tell it: go to 1 radian, about 57 degrees. A motor inside turns a gear, and the gear turns the forearm. You send the command. Did the forearm get there?
You cannot know from the command alone. The forearm may be heavy. The gear may have a small gap. Someone may have bumped the arm. The motor controller sent the right current and the arm still ended up somewhere else. A controller that never looks at the result is working blind.
So the first part of this lesson is about eyes. An encoder is a sensor that turns shaft rotation into numbers a microcontroller can read. Think of the click wheel on an old mouse: each click is one small step of rotation, and counting clicks tells you how far the wheel turned. The second part is about what firmware does with those numbers. It closes loops: measure, compare with the goal, push the other way, and repeat a thousand times a second.
Here is the simplest version. A joint makes 20 small moves of 0.1 rad each. On some moves the gear slips and the joint moves a little less than commanded. Without an encoder, the controller only knows what it asked for, so every slip stays hidden and the errors add up. With an encoder, the controller reads the real angle after each move and asks for the missing part on the next one.
Blue is where the controller believes the joint is. Warm is where it really is. Raise the slip rate, then switch the encoder on and off.
Illustrative: each move has the stated chance of slipping, and a slip loses between 0.02 and 0.06 rad. The slips come from a fixed seed, so every visit shows the same ones. The encoder is ideal here; Chapters 1 to 4 say what a real one gives you.
With no encoder, the error is the sum of all the slips: a random walk that only grows. With an encoder, the error never exceeds the last slip, because the next move repairs the rest. That one change, reading the real angle, is the whole idea of feedback.
A real joint asks for more than a repair after each move. It must reach the target fast, without overshoot, and without shaking. No single rule does all three well. Firmware therefore splits the job into three nested loops, each with one small task.
The innermost loop is the current loop. It makes the motor current equal to a requested value, because motor torque follows current. The middle loop is the velocity loop. It asks the current loop for whatever torque makes the shaft turn at the requested speed. The outer loop is the position loop. It looks at the angle error and asks the velocity loop for a speed. This stack is called a cascade: each loop's output is the next loop's goal.
Each loop needs a measurement. The position loop needs an angle. The velocity loop needs a speed, which firmware must work out from angles. The current loop needs a current from an ADC. That is why this lesson starts with encoders. Every loop above the current loop lives on what the encoder tells it.
The device you saw at the top of the page is a model of one joint. It has a motor, a loose gear, a load, an encoder and a 1 kHz control loop. Press its buttons now and see three outcomes: a position loop on its own rings, a tuned cascade settles, and a cascade with the gains turned too high chatters. By the end you will know why, and you will tune it yourself in Chapter 9.
The model is honest but simple. It runs in your browser, not on silicon. Each core chapter ends with an On real hardware note: a board and one measurement you can repeat. The examples assume an Arm Cortex-M part from the STM32 family, as in timers, PWM and sampling. The motor itself comes from Motors for Firmware People. For the control theory of PID and tracking, see trajectory tracking with PID and LQR and the control lesson in the navigation series. The current loop's inside, the Clarke and Park transforms, belongs to the motor-control firmware lesson (pai-fw-06), and Chapter 5 only borrows what it needs.
Chapter 1
Read two square waves a quarter of a cycle apart and turn them into a signed count of steps
Spin a bicycle wheel with a clothespin touching the spokes. Each spoke makes a click. Count the clicks and you know how far the wheel turned. Now push the wheel backward by one spoke and forward again. The clicks sound the same both ways. One click wire cannot tell forward from back.
The fix is a second click wire, placed so the two disagree in a useful way. That is the whole idea of a quadrature encoder. It has a disc with evenly spaced slits and two sensors, called A and B. Each sensor outputs a square wave: high where light passes, low where it is blocked. The sensors sit so that B is shifted a quarter of a slit pitch from A. That is a 90 degree phase difference, and the word quadrature means a quarter.
Turn the disc one way and A goes high first, then B. Turn it the other way and B goes high first. So the order of the changes tells you the direction. The pair (A, B) walks through four states in a fixed loop: 00, then 10, then 11, then 01, and back to 00. Forward is that loop one way, reverse is the other way. Only one of the two bits changes at each step. The sequence is a two-bit Gray code, a code where neighbours differ in one bit. Wikipedia notes that each A and B sample is effectively a two-bit Gray code, because in normal running A and B never change together.
That one-bit rule is a gift. If the firmware ever sees both bits change at once, it knows it missed a step. We use this in Chapter 2.
A square wave has two edges per cycle, and there are two waves. So each slit gives four state changes. The encoder's label counts slits: PPR or CPR, pulses or cycles per revolution. A x4 multiplier counts every state change, so the count rate is four times the pulse frequency of A.
Take an encoder labelled 2,048 PPR. Counting every edge gives 4 × 2,048 = 8,192 counts per turn. One count is 360 / 8,192 = 0.044 degrees. At 3,000 rpm the shaft turns 50 times a second. A then runs at 2,048 × 50 = 102.4 kHz, and the count rate is 409,600 counts per second. Firmware that polls a pin cannot keep up with that for long, which is why Chapter 2 hands the job to a timer.
The device below uses a toy disc with only 8 slits, so one slit pitch is 45 degrees. The waveforms are drawn against shaft angle. Drag the angle slider and watch the state step through the loop. Three counters run side by side: one counts only rising edges of A (1x), one counts both edges of A (2x), one counts every state change (4x).
Drag the angle. The pink line marks the shaft. Then press Shake at an edge: the shaft rocks back and forth across one edge, as a vibrating motor would.
A model of an 8-slit disc, so one slit pitch is 45 degrees and B is shifted by 11.25 degrees. A real encoder has hundreds or thousands of slits. The 1x counter counts rising edges of A and takes the direction from B. The 2x counter counts both edges of A. The 4x counter uses the state table below. All three step the angle in 0.25 degree steps so none misses an edge.
Drag forward to 45 degrees: the 1x counter reads 1, the 2x counter reads 2 and the 4x counter reads 4. Drag back and they fall again. Now shake at an edge. The 4x counter goes up by one and down by one for every rock, and ends where it started. The 1x counter only sees the rising edge, never the falling one, so each rock adds a count it never takes back. A decoder that tracks the full state keeps its books balanced.
The 4x decoder is a lookup. Take the old state (2 bits) and the new state (2 bits). That makes a 4-bit index into a table of 16 entries. Each entry is +1 (one step forward), −1 (one step back), 0 (no change) or an error (both bits changed, so a state was skipped).
c, a 4x quadrature decoder (state table) /* state = (A << 1) | B. Forward order: 00 -> 10 -> 11 -> 01 -> 00. */ static const int8_t QEM[16] = { /* new: 00 01 10 11 old: */ 0, -1, 1, 2, /* 00 */ 1, 0, 2, -1, /* 01 */ -1, 2, 0, 1, /* 10 */ 2, 1, -1, 0 /* 11 */ }; static uint8_t prev; static int32_t count; static uint32_t errors; void qdec_update(uint8_t a, uint8_t b) { uint8_t now = (a << 1) | b; int8_t d = QEM[(prev << 2) | now]; if (d == 2) errors++; /* skipped a state: count the fault */ else count += d; prev = now; }
Read the row for old state 00. A move to 10 gives +1, the forward step. A move to 01 gives −1, the reverse step. A move to 11 gives 2, which marks an error. Every row follows the same shape. The code does one table read and one add, so even a slow part can run it in an interrupt.
An incremental encoder remembers nothing. It reports changes, and your counter sums them. After power-up, the counter reads zero wherever the shaft happens to rest. Many encoders add a third output, Z or the index, that pulses once per revolution at a fixed shaft angle. Firmware drives the joint slowly until it sees Z, and then knows the true angle. This is called homing. Chapter 3 shows encoders that skip homing by reporting an absolute angle.
Symptom: the joint is parked, yet the counter reads a few counts more each minute. Measurement: put a scope on A and B at the MCU pin. Look for spikes, slow edges or ringing near the switching of the motor drive. Fix: use differential line receivers on long cables, an RC or digital filter on the inputs, and a decoder that follows the full state, as above. A glitch that makes one wrong step usually makes a matching wrong step back, and the 4x table nets them out.
On real hardware. Use an STM32 Nucleo and any 100 to 600 PPR optical encoder. Probe A and B with a scope or a logic analyzer. Turn the shaft by hand one full turn and confirm that A and B are a quarter cycle apart and that the 4x count rises by exactly 4 times the PPR.
Chapter 2
Choose between polling, interrupts and a timer, and learn the sample-rate rule that stops silent count loss
A joint motor spins at 3,000 rpm and the encoder gives 8,192 counts per turn. That is 409,600 state changes every second, one every 2.4 microseconds. Your control loop runs once per millisecond. What does the loop see?
If the loop reads pins A and B once per tick, it sees the state at one instant and nothing in between. Between two reads, the state may have walked through 400 steps. The pins are not a count. They are a picture of one moment. Firmware needs something that watches every moment.
First, polling: read the pins in a fast loop. It works for a hand knob and fails for a motor. Second, an edge interrupt on each pin. Every edge runs the decoder from Chapter 1. This is exact, but each interrupt costs time. Suppose one costs 1 microsecond (an illustrative figure). At 409,600 edges a second that is 41% of the CPU, spent on counting.
Third, hardware counting. Most microcontrollers have a timer that can take A and B as inputs and run the state table in silicon. On an STM32, the general-purpose timers have an encoder interface mode. Set the slave mode field SMS in the TIMx_SMCR register to 011, and the counter counts on edges of both TI1 and TI2. The counter then acts like a clock with a direction. The reference manual says the direction bit DIR in the TIMx_CR1 register is recalculated at each transition on either input. The CPU does nothing. It reads the counter whenever it wants a position.
c, STM32F411 (Nucleo-F411RE): TIM3 as a 4x quadrature counter on PA6 (A) and PA7 (B) /* PA6/PA7 set to alternate function 2 (TIM3_CH1/CH2), pull-ups on; check your part's AF table */ RCC->APB1ENR |= RCC_APB1ENR_TIM3EN; TIM3->ARR = 0xFFFF; /* count 0..65535, then wrap */ TIM3->CCMR1 = (1 << 0) | (1 << 8) /* CC1S=01, CC2S=01: inputs on TI1, TI2 */ | (3 << 4) | (3 << 12); /* IC1F, IC2F: filter, N=8 samples (see RM filter table) */ TIM3->SMCR = TIM_SMCR_SMS_0 | TIM_SMCR_SMS_1; /* SMS=011: encoder mode 3, count both inputs */ TIM3->CR1 |= TIM_CR1_CEN; /* run */ int32_t enc_position(void) { /* call at a fixed rate, e.g. in the 1 kHz loop */ static uint16_t last; static int32_t pos; uint16_t now = TIM3->CNT; pos += (int16_t)(now - last); /* signed difference survives the wrap */ last = now; return pos; }
On the Nordic nRF52840 there is no counting timer. A block called QDEC samples A and B at a period you pick, SAMPLEPER, from 128 microseconds to 131,072 microseconds. It accumulates steps in a register ACC that holds −1,024 to 1,023. If the state moves by two steps between samples, the manual says that double transition is not accumulated; it is counted separately in ACCDBL. This sampling rule matters, and the next section shows why.
The STM32 counter above is 16 bits wide, so it wraps from 65,535 to 0. With 8,192 counts per turn that happens every 8 turns. Position cannot be the raw counter. The code keeps a 32-bit running position and adds the signed difference since the last read. In 16-bit arithmetic, now − last is correct even across the wrap. Take last = 65,530 and now = 4. Unsigned, the difference is 10, which is the true 10 steps forward. The rule: read the counter at least often enough that the shaft cannot move 32,768 counts between reads. At 8,192 counts per turn and a 1 kHz read, that is a speed limit of 4 turns per millisecond, far above any joint. (Some timers, for example TIM2 and TIM5 on many STM32 parts, are 32 bits wide. Check your part's datasheet.)
A sampled decoder, such as QDEC or a polled GPIO loop, sees the state only at sample instants. It decodes correctly only if the state moved at most one step between two samples. That means the sample rate must exceed the count rate. If it does not, two things go wrong. A jump of two steps is detectable: it is the "both bits changed" case of the table. A jump of three steps looks like one step backward. A jump of four steps looks like no change at all. Both are wrong with no warning. Try it.
The lines are A and B at the chosen count rate. The dots are the instants when firmware reads the pins. Raise the count rate or lower the sample rate until the decoder starts to lose steps.
A model: the shaft turns at a constant speed, so the state changes at the count rate you set, and the decoder is the table from Chapter 1. The count is taken over 20 ms. Real encoders also have jitter, which makes the safe margin larger than the bare rule.
Set the count rate to 40 thousand per second and the sample rate to 100 kilohertz: every step is seen. Slide the sample rate down below 40 kilohertz and steps begin to vanish. When the count rate is exactly four times the sample rate, whole cycles vanish: the decoder reports no error and counts nothing. That silent case is the one to fear.
Symptom: after a few minutes of running, the joint's zero has moved. The arm stops a little to one side each time. Measurement: use the index pulse. On an encoder with a Z output, the counter should change by exactly 4 times the PPR between two index pulses. Log the count at each Z. A different number means steps were lost, and the difference says how many. Fix: use the timer's hardware mode, enable its input filter against spikes, shield and twist the cable, and count skipped-state errors as in Chapter 1.
On real hardware. On a Nucleo-F411RE, wire the encoder to PA6 and PA7, run the code above, and print the position. Turn the shaft one revolution by hand and check the change equals 4 times the PPR. Then spin the motor fast and log the count at each index pulse. Any change from run to run is a lost or invented step.
Chapter 3
Read an angle over SSI, BiSS or SPI, check it with a CRC, and account for the time the message takes
Power up a robot arm that was switched off with its elbow bent. An incremental encoder starts its counter at zero, and zero means nothing. The firmware must drive the joint to the index pulse and only then knows where it is. For a surgical arm or a heavy robot, moving blind at start-up is a risk.
An absolute encoder solves this. Every shaft angle has its own code, so the position is known the instant power returns. Wikipedia puts it plainly: an absolute encoder maintains position information when power is removed. A multi-turn absolute encoder adds geared wheels that count whole revolutions on top of the angle within one turn.
Inside, the angle comes from a coded disc read by light sensors, or from a magnet read by a magnetic sensor. The chip turns it into a number, say 20 bits. That is 220 = 1,048,576 positions per turn, or 0.00034 degrees each. The number must get to your microcontroller. Sending 20 wires in parallel is clumsy, so absolute encoders send the number in a short serial message.
SSI, the synchronous serial interface, is the simplest. The master sends a train of clock pulses. When the clock starts, the encoder freezes its current angle. It then sends one bit per rising edge, most significant bit first. When the master stops the clock for longer than a timeout the standard calls tm, the encoder ends the transfer and takes a fresh angle. Wikipedia lists clock rates from 100 kHz to 2 MHz, and RS-422 example links of 90 kbit/s at 1.2 km and 10 Mbit/s at 5 m. Longer cable means a slower clock.
BiSS (bidirectional, serial, synchronous) is an open standard for the same job, aimed at motion control. BiSS C is used for motor feedback. The BiSS site lists cycle times below 10 microseconds and a register channel for configuration that works without interrupting position data. Wikipedia gives a maximum data rate of 10 MHz over 1 km of RS-422 cable and up to 64 bits of sensor data per slave. Both sources say the link is protected by a CRC.
Many small magnetic angle chips skip these and use plain SPI: the microcontroller pulls chip select low, clocks out one 16-bit word and reads the angle with a few status or parity bits. The bit layout differs per chip, so read the datasheet. The firmware idea is the same: one transaction, one number.
A long cable beside a motor drive picks up noise. One flipped bit in the middle of the angle word turns 0.5 degrees into 6 degrees. SSI as drawn has no check, so firmware accepts the wrong angle. A CRC, a cyclic redundancy check, is a short code the sender computes from the data and appends. The receiver recomputes it. If the two codes differ, the frame is bad, and the firmware drops it and uses the last good value.
The device below sends a frame of 20 position bits. The BiSS-style frame adds a 6-bit CRC. The CRC here is an illustrative one with polynomial x6 + x + 1, so you can see the idea; the real CRC and the full frame layout are in the BiSS specification. Press the flip button to corrupt one bit on the wire.
Each box is one clock. Purple bits are the angle, pink bits are the check, grey boxes are framing. Slide the clock and the speed, then flip a bit.
A model. The frame is 2 framing clocks, 20 angle bits and, in BiSS style, 6 CRC bits, which is an illustrative layout, not the standard's. The encoder freezes the angle at the first clock, as SSI does. Real links add line delay and the encoder's own processing time; both are left out. The clock steps from 0.1 to 10 MHz on a log scale.
With the SSI-style frame, flipping bit 14 changes the angle by 16,384 counts, about 5.6 degrees. The firmware gets no hint. With the CRC, the received code no longer matches, the frame is rejected, and the read-out says so. That is the reason to prefer a link with a CRC for a joint that carries weight.
A frame of 28 clocks at 1 MHz takes 28 microseconds. The angle was frozen at its first clock. By the time the last bit arrives, the shaft has moved on. At 3,000 rpm the shaft turns 18,000 degrees a second, so 28 microseconds is 0.5 degrees, more than 1,400 times the encoder's resolution. The angle you hold is not the angle now. It is the angle one frame ago.
Two fixes work together. Raise the clock, as far as the cable allows. And add a correction: estimated speed times the age of the data. Toggle the correction in the device and watch the age error shrink. This also shows why a position loop must know exactly when its sample was taken: Chapter 4 and Chapter 10 come back to it.
Symptom: the joint twitches now and then, and a log shows single position samples a few degrees off, then back. Measurement: count CRC failures per minute, and capture the clock and data lines with a logic analyzer. Look for ringing, a slow edge, or a clock that is faster than the cable allows. Fix: lower the clock, use the differential RS-422 pair, terminate the line, and reject frames with a bad CRC instead of using them. Count how many you reject: a rising count is an early warning.
On real hardware. On a Nucleo with an SPI magnetic angle chip, read the angle in a loop and print it. Watch chip select and clock on a logic analyzer and measure the time from chip select falling to the last clock. That is your sample age. Rotate the shaft at a steady speed and check that the age times the speed matches the offset you see.
Chapter 4
Turn a stream of position counts into a speed, and see why every cure for noise costs time
A car has an odometer that counts kilometres and a speedometer that shows speed. Your joint has only the odometer. The encoder gives position. The velocity loop needs speed. So the firmware must make a speedometer out of an odometer.
The idea is the one from school: speed is distance divided by time. Read the position now, read it one tick ago, subtract, and divide by the tick length. This is a backward difference. Wikipedia calls this the frequency method: read counts at two times and divide the change by the elapsed time.
The encoder does not give a smooth position. It gives whole counts. One count is a step of q radians. Take the 2,048 PPR encoder with 4x decoding: 8,192 counts per turn, so q = 2π / 8,192 = 0.000767 rad. At a 1 ms tick, one count of change means a speed of 0.000767 / 0.001 = 0.767 rad/s, or 7.3 rpm. The speed can only be 0, 7.3, 14.6 rpm and so on. Anything in between is rounded.
Now spin the shaft at 10 rpm, a slow joint. In some ticks it moves one count, in others two. The estimate hops between 7.3 and 14.6 rpm although the true speed is steady. That hop is quantization noise: error caused only by rounding the position to whole counts. For the theory of rounding noise, see quantization noise in signal processing.
The noise matters most through the velocity loop. That loop multiplies the speed error by a gain. Say the gain is 0.4 A per rad/s. A one-count hop of 6.1 rad/s on a 256 PPR encoder (q = 0.00614 rad) becomes a 2.5 A hop in the current command. That is the chatter you saw in the hero when the cascade was "too hot".
Divide over more ticks. Use the position N ticks ago instead of one tick ago. The speed step becomes q / (N × Ts). With N = 4 and Ts = 1 ms the step shrinks to 0.19 rad/s, four times smaller. But there is a price. A difference over N ticks is the average speed over that window, and an average describes the middle of the window. So the estimate is late by about N × Ts / 2. For N = 4 that is 2 ms.
Smooth the raw speed with a first-order filter, which blends in a fraction of the new reading each tick. A filter with cutoff fc adds a delay of about 1 / (2π fc) seconds. A 100 Hz cutoff adds 1.6 ms. Lower the cutoff for quieter speed and the delay grows. The PID literature makes the same point about derivative terms: a low-pass filter tames the noise, and the price is lag.
At low speed there may be no count at all in a tick, and the estimate reads zero. The second method in Wikipedia is by period: measure the time between pulses, so the measurement is triggered at positions instead of at times. This avoids position quantization and brings time quantization, so it needs a fast clock. The M/T method combines both: count M edges in a window that ends on an edge, and time that window with a fast clock. It is accurate from slow to fast. The cost is a window whose length is not fixed, so the delay changes with speed.
The shaft below turns at 15 rad/s with a 1.5 Hz wobble of 8 rad/s on top. The warm line is the true speed. The purple line is what firmware would compute from the quantized position. Change the encoder, the window and the filter.
Start with a coarse encoder and a window of 1: the estimate is steppy. Raise the window and watch the steps shrink and the line slide to the right.
A model: a 1 kHz tick, 4x decoding, position rounded down to whole counts. Noise is the rms of the estimate minus the true speed as it was at the time the estimate is centred on. The delay is N × 1 ms / 2 plus 1 / (2π fc) for the filter. All illustrative; a real signal has more error sources.
At 256 PPR and a window of 1 the speed steps are 6.1 rad/s tall, almost as tall as the wobble. At 4,096 PPR they shrink to 0.38 rad/s. A longer window or a filter does the same job for less hardware, and it delays the estimate. There is no setting with both zero noise and zero delay. The best you can do is pick the delay your loop can tolerate, which Chapter 6 measures.
c, windowed velocity with a one-pole filter, called every 1 ms #define N 4 /* window length in ticks */ static int32_t hist[N + 1]; static uint8_t h; float velocity_rad_s(int32_t pos_counts) { hist[h] = pos_counts; h = (h + 1) % (N + 1); int32_t old = hist[h]; /* the position N ticks ago */ float raw = (float)(pos_counts - old) * (RAD_PER_COUNT / (N * TS)); static float v; v += ALPHA * (raw - v); /* ALPHA = 1 - expf(-TS * 2 * PI * FC) */ return v; }
Symptom: at a very slow, steady speed the joint growls or ticks, and the current command swings up and down. Measurement: log the speed estimate at a constant slow command. If it hops between 0 and one step, the encoder is too coarse for the window. Fix: use a longer window at low speed, switch to M/T timing, or fuse position and the motor model in an observer such as a Kalman filter. A higher PPR also works, but cost and cable limits apply.
On real hardware. On a Nucleo-F411RE with a geared motor, read the TIM3 count in a 1 kHz interrupt and send it over the UART. Run the motor at a constant slow command and compute the speed with N = 1 and N = 8 offline. Plot both. Then give the motor a step in speed and measure how many milliseconds the N = 8 line takes to catch up.
Chapter 5
Tune the innermost loop with two gains taken straight from the motor, and see what limits how fast it can be
You want the joint to push with a force you choose. A motor's torque is proportional to its current: double the current and you double the torque. So a torque controller is really a current controller. The innermost loop of the cascade makes the motor current equal to a number the next loop asks for.
Why not just send a voltage and hope? Because the winding fights back. When you apply voltage to a coil, the current does not jump. It climbs, because the coil stores energy in a magnetic field. How fast it climbs is set by the coil itself. That is the plant this loop must control.
Treat one winding as a resistor R in series with an inductor L. The voltage law says: v = L · di/dt + R · i. The inductor term is the part that opposes sudden change. Apply a fixed voltage and the current rises smoothly to v / R with a time constant of L / R. For a small joint motor, say R = 0.5 ohm and L = 0.2 millihenry, L / R = 0.4 ms (illustrative values). The winding alone takes about 1 ms to reach full current.
This lesson treats the winding as one such circuit. In a real three-phase motor, the transforms of field-oriented control reduce it to two circuits like this one, called the d and q axes. The motor-control firmware lesson (pai-fw-06) builds those transforms, and torque comes from the q-axis current. For this chapter, one winding is enough.
A PI controller sets the voltage from the current error e: v = Kp · e + Ki · ∫e dt. The first term pushes in proportion to the error. The second term adds up the error over time, so a small error that lasts still builds a push. That removes any steady error.
Here is the trick. Choose the two gains from the motor: Kp = L · ωc and Ki = R · ωc, where ωc is the bandwidth you want in radians per second. The controller's own time constant Kp / Ki then equals L / R, which cancels the winding's slow climb. What is left is a loop that behaves like a simple integrator, and the closed loop becomes a first-order response with time constant 1 / ωc. You choose the speed, and the gains follow.
For a 1 kHz bandwidth: ωc = 2π × 1,000 = 6,283 rad/s. Kp = 0.0002 × 6,283 = 1.26 V/A. Ki = 0.5 × 6,283 = 3,142 V/(A·s). Time constant 1 / 6,283 = 0.16 ms, so a step takes about 2.2 × 0.16 = 0.35 ms to go from 10% to 90%.
ODrive's documentation uses the same idea: its current gains are set automatically from a single setting called the current control bandwidth.
Why not pick 20 kHz and be done? Two things stop you. The first is time. The firmware samples the current, computes a voltage, and the PWM applies it in the next period. That is at least one sample of delay. A loop with delay turns unstable when you push it too hard. A common rule of thumb is to keep the bandwidth under a tenth to a twentieth of the loop rate. The second is voltage. A 10 A step at 1 kHz needs Kp × 10 = 12.6 V at the first instant. At 3 kHz it needs 37.7 V, more than a 24 V bus can give. The command saturates and the response slows down.
The top line is the current after a 10 A request. The lower line is the voltage the controller applies, with the 24 V limit marked. Raise the bandwidth until it breaks.
A model: a winding of 0.5 ohm and 0.2 mH, a 24 V bus, and a loop that applies its voltage one sample late. The gains are Kp = L · ωc and Ki = R · ωc. The motor values are illustrative. A real drive adds dead time, ADC filtering and back-EMF.
At a 20 kHz loop and 1,000 Hz the step rises in about 0.35 ms with only a couple of percent overshoot. At 2,000 Hz the current overshoots by a third. At 5,000 Hz it rings and the voltage hits its limit again and again. Switch to a 40 kHz loop and the same bandwidths behave much better: more samples per second means less delay. This is why fast drives run the current loop at the PWM rate or faster.
Symptom: the motor emits a high-pitched tone and runs hot. Measurement: record the phase current at the ADC rate while stepping the request. Overshoot of more than about 10%, or a ringing tail, says the loop is too fast for its delay. Fix: lower the bandwidth, raise the PWM and loop rate, cut the delay between the ADC trigger and the PWM update, or check the bus voltage, since a bus that sags causes saturation. Timers, PWM and sampling shows how to line the ADC trigger up with the PWM.
On real hardware. On an STM32 Nucleo with a motor-driver expansion board and a small motor held still, command a 2 A step and capture the current with a current probe on a scope, or with the ADC and DMA. Measure the 10 to 90% rise time and compare with 2.2 / ωc. Lock the rotor so the motor does not turn.
Chapter 6
Ask the current loop for just enough torque to hold a speed, and learn what breaks when the loops are too close in speed
You are driving with cruise control set to 100 km/h. A hill appears and the car slows. The controller presses the pedal harder until the speed returns. The pedal sets how fast the speed changes. It does not set the speed itself. That is how a motor works too: current sets torque, torque sets acceleration, and acceleration changes speed.
Write that down. With inertia J and torque constant Kt, J · dω/dt = Kt · i. The speed ω is the running total of the acceleration, so the shaft behaves like an integrator: a thing that adds up what you feed it. Let A = Kt / J be the acceleration you get per amp. In this lesson's model A = 4,000 rad/s² per amp (illustrative).
The velocity loop looks at the speed error, the target speed minus the estimated speed from Chapter 4, and asks the current loop for current. With a proportional gain Kv in amps per rad/s, the current is i = Kv · e. Plug that into the integrator and the speed approaches its target like a charging capacitor, with a rate of ωv = Kv · A. Pick the speed bandwidth and the gain follows.
Kv = 0.06 A per rad/s gives ωv = 0.06 × 4,000 = 240 rad/s, which is 38 Hz. The time constant is 1 / 240 = 4.2 ms, so a speed step takes about 2.2 × 4.2 = 9 ms to go from 10% to 90%.
Friction and gravity still push the speed off target, and a pure proportional loop leaves a small steady error. The fix is the integral term: a running sum of the error that keeps adding current until the error is gone. ODrive's controller is exactly this shape: the velocity loop is a PI that outputs a current command, with the current integral fed by the velocity error times a gain. One more rule from the PID literature: the current has a limit, so clamp the integral at that limit. Wikipedia lists limiting the integral term to preset bounds as one of several remedies for windup, where the sum grows far past what the output can deliver and then causes overshoot.
The velocity loop treats the current loop as instant: ask for 2 A, get 2 A. It is not instant. It has its own bandwidth, from Chapter 5. Think of steering a boat with a slow rudder: if you correct as fast as the rudder responds, you overshoot and swing back. The same happens here. If the velocity loop is almost as fast as the current loop below it, the late torque makes it ring.
The usual rule of thumb is to keep each inner loop several times faster than the loop outside it, often five to ten times. The device shows the rule in numbers. It also adds the delay from Chapter 4: the speed estimate arrives late, which acts like extra lag in the same way.
The shaft is asked to go from rest to 20 rad/s. Raise the gain, then make the inner loop slower or add delay to the speed estimate, and watch where it starts to ring.
A model: a single mass with A = 4,000 rad/s² per amp, a little friction, a first-order current loop, a 1 kHz controller, a PI whose integral gain is 20 times the proportional gain, and a 6 A current limit with the integral clamped. The delay is added to the speed feedback. All values are illustrative; the sample-and-hold of the 1 kHz loop adds about a millisecond of lag of its own.
With the 2,000 Hz current loop and no delay, Kv = 0.15 gives about 3% overshoot: the speed bandwidth is 600 rad/s (95 Hz) and the inner loop is far above it. Switch to the 150 Hz inner loop with the same gain and the overshoot jumps to about 26%, because the two loops are now only about a factor 1.6 apart. Add 2 ms of delay to the 0.15 gain and it rings hard and never settles, while 0.06 still settles with about 20% overshoot. Two ways to keep the loop calm: lower the gain, or fix the delay at its source.
Suppose the current loop is at 600 Hz and you accept 1 ms of total delay from the estimate. First pick a speed bandwidth about one fifth of the inner one, 120 Hz or 754 rad/s. Then Kv = 754 / 4,000 = 0.19 A per rad/s. Check against the delay: 754 rad/s × 0.001 s = 0.75 rad, about 43 degrees of lost phase, more than you want. Drop the target to 60 Hz: Kv = 0.094, lost phase 0.38 rad or 22 degrees. The delay, not the arithmetic, picks the bandwidth. This is why Chapter 4's cure for noise is paid for here.
Symptom: at standstill or low speed the motor growls at a few hundred hertz and the current command swings. Measurement: log the current command and the speed estimate during a small speed step. A ringing period near 1 / (the velocity bandwidth) and a current command that touches the limit say the loop is too fast for its delay. Fix: halve the gain, or shorten the estimate window, or raise the inner-loop bandwidth, in that order of cost.
On real hardware. On an STM32 Nucleo with a motor and encoder, command speed steps of about 10% of the top speed with the position loop off. Record the speed estimate at 1 kHz. Measure the overshoot and the ring period, then double the gain once and measure again.
Chapter 7
Turn a distance to go into a speed to travel, and see why a moving target leaves the loop behind unless you tell it the speed
You ask a friend to walk to the door. A sensible friend walks fast when the door is far and slows as it gets close. They do not need to compute anything clever. Speed is simply proportional to the distance left. That is the whole position loop.
In code it is one line: v_cmd = Kp * (target - angle). The result goes to the velocity loop as its goal. Kp has units of (rad/s) per rad, which is 1/s. Because the velocity loop below makes the speed follow its command, the position is the running total of that speed. A joint is an integrator again, and a plain proportional gain is enough. ODrive's documentation describes its position loop exactly this way: P only, with the velocity command equal to the position error times the position gain, plus an optional feedforward.
Feed the speed command into the integrator. The error obeys de/dt = −Kp · e. The solution is e(t) = e0 · e−Kpt, a smooth decay with no overshoot. Its time constant is 1 / Kp. With Kp = 20 per second, the time constant is 50 ms and the error falls to 2% in four time constants, 200 ms. That is the ideal. In the real stack, the velocity loop's own lag bends it: a very high Kp brings overshoot and ringing.
So the position gain obeys the same rule as the loops before it. Keep the position bandwidth several times below the velocity bandwidth. The tuned velocity loop of Chapter 6 had a bandwidth of 240 rad/s. A Kp of 20 per second is twelve times lower, which leaves a wide margin. Pushing Kp up to 60 is still about four times lower and starts to show small overshoot in the model.
For a 3 rad move the first speed command would be 3 × 20 = 60 rad/s. The motor, the gear or the cable may not allow that. So firmware clamps the speed command to a limit. The joint then cruises at the limit, and the proportional rule takes over for the last stretch. ODrive exposes this limit as a velocity limit setting, and recommends a current limit with headroom above the planned values.
Now ask for something harder: follow a ramp that moves at a steady 8 rad/s. To keep moving at 8 rad/s, the loop must output a speed command of 8 rad/s. A proportional loop produces speed only from error, so it needs an error of e = v / Kp = 8 / 20 = 0.4 rad. This following error is the lag between a moving target and the joint. It is not a fault of the sensor or the motor. It is the price of a loop that learns about motion only when the joint falls behind.
The cure is feedforward: if you already know the speed the target will have, add it straight into the speed command. Then the loop only has to fix the leftover. In the device, the command is a ramp from 0 to the move distance at 8 rad/s, followed by a hold. Switch feedforward on and watch the following error collapse.
The dashed line is the ramp, and the warm line is the joint. The lower plot is the gap between them. Raise the position gain, then toggle feedforward.
The full joint model from the hero, with the gap set to zero so only the loops show. Tuned velocity loop (gain 0.06, integral 0.3), 2,048 PPR encoder, 1 kHz, 6 A limit, speed limit 30 rad/s. The ramp speed is 8 rad/s. Illustrative numbers; the model is written out in Chapter 9.
At a gain of 20 per second, the model's following error peaks at about 0.37 rad, close to the 0.40 that e = v / Kp predicts. With feedforward it falls to about 0.06 rad. The small rest comes from the velocity loop's own lag. Feedforward has a cost: when the ramp ends, the commanded speed drops to zero at once, and the real speed takes a few milliseconds to follow, so a small overshoot appears. Planners soften that by rounding the corner of the ramp.
The velocity loop already has an integrator. Adding a second one on position makes a loop with two integrators in series, which tends to oscillate and winds up badly when the current limit bites. Leave the position loop proportional. If a steady load still leaves a small error, let the velocity integrator handle it, as Chapter 8 shows.
Symptom: the joint arrives, sails past the target, and comes back. Measurement: record the target, the angle and the speed command during a 1 rad step. If the speed command changes sign near the target and the angle crosses it, the position loop is too fast for the velocity loop. Fix: lower Kp. ODrive's tuning guide uses the same order: raise the position gain by about 30% per try until you see overshoot on command steps, then back it down until the overshoot is gone.
On real hardware. On a Nucleo with a geared motor and encoder, send a 1 rad step and a slow ramp. Log the target and the angle at 1 kHz. Measure the peak following error on the ramp and compare it with the speed divided by Kp. Then add the feedforward term and measure again.
Chapter 8
See how a small gap between gear teeth either hides the truth from the loop or sits inside it and makes it hunt
Hold a bicycle pedal and wiggle it without moving the bike. The pedal moves a little before the wheel responds. That small free play is the slack in the chain. Gears have the same slack. Between two meshed teeth there is a gap, so when the motor reverses direction the output shaft waits until the gap closes.
Engineers call this backlash. Wikipedia defines it as clearance or lost motion in a mechanism caused by gaps between the parts. It comes from teeth cut deeper than ideal, from allowances for lubrication, manufacturing error and heat, and from wear. Wikipedia also states the control consequence plainly: the dynamic response of backlash, essentially a delay, makes the position loop less stable and thus more prone to oscillation.
Where you place the encoder decides what the loop knows about the gap.
Encoder on the motor shaft. This is the usual choice. A gearbox multiplies the angle, so a motor-side encoder with a given count gets finer resolution at the output. The gap is outside the loop: the loop sees only the motor, which is stiff and well behaved. The cost is that the loop cannot see the load. If gravity or a push keeps the load on one side of the gap, the motor can sit exactly where you commanded while the load rests up to half the gap away. In the model, with a 0.06 rad gap and gravity on, the load stops 0.03 rad short, exactly half the gap.
Encoder on the load shaft. Now the loop sees the real position. But the gap is inside the loop. While the motor crosses the gap, the load does not move, so the loop sees no response to its torque. That is a delay, the thing Wikipedia says hurts stability. The integral term keeps adding current while nothing happens, then the gap closes and the load jerks. The result is hunting: the joint swings back and forth around the target forever, a limit cycle in which the loop keeps crossing the gap.
A common compromise is two encoders. The motor-side one feeds the velocity loop, which needs a clean, quick speed estimate. The load-side one feeds the position loop, which needs the true angle but can be slower. Wikipedia mentions the same family of fixes: controllers can add extra motion or use closed-loop position sensing to offset backlash, and mechanical designs use split gears with a spring or preloaded nuts to close the gap.
The joint moves 1 rad and then holds for a few seconds. The lower plot is the error between target and load. Turn gravity on and off, widen the gap, and raise the integral gain.
The joint model from the hero: unit motor inertia, a load 1.5 times heavier on the far side of the gap, a stiff damped contact, a 2,048 PPR encoder, a 1 kHz cascade with position gain 20, speed gain 0.03 and the integral gain you set. Gravity is a constant torque on the load. Illustrative numbers.
Start with the encoder on the motor and gravity on: the load settles steadily, 0.03 rad off, exactly half the gap, and the motor-side loop reports success. Switch to the load encoder and that error closes to nothing, because gravity keeps the teeth in contact and the loop never crosses the gap. Now turn gravity off and keep the load encoder: the load hunts, and the ripple grows toward the width of the gap as you raise the integral gain. The same hardware has three different behaviours.
Keep the integral gain low on a loop that sees the gap: the integral is what pushes through the gap again and again. Use a motor-side speed loop with a load-side position loop. Add a small preload torque that keeps the teeth in contact in one direction. Or give the loop a dead band: stop correcting when the error is smaller than the gap. Each trades a small accuracy loss against stability. The design pays for itself when the joint carries a steady load, as arms do.
Symptom: the joint hums or ticks at rest and the position wanders by a fraction of a degree. Measurement: log the load angle during a long hold. A steady swing with a period of a fraction of a second and an amplitude near the gap width is hunting. A constant offset of half the gap is the motor-side view. Fix: for hunting, lower the integral gain, add preload, or move the position loop to a slower rate. For the offset, add a load-side sensor or accept the offset.
On real hardware. On a Nucleo with a geared motor that has a second encoder or a potentiometer on the output, hold a position and push the output by hand. Compare the two angles. The difference when you push each way is the backlash. Log the load angle for 10 seconds with only the motor-side loop closed and note the offset.
Chapter 9
Put every loop together, follow a tuning recipe from the ODrive docs, and make four checks pass at once
You now have all the parts. An encoder gives counts, firmware makes a speed from them, and three loops use that speed and the angle. This chapter is the payoff. You get the whole joint and every knob in one device. The task: make the joint land fast, without overshoot, without chatter and without hunting.
The model is the same one that ran in the hero and in Chapters 7 and 8. It has these parts, each from an earlier chapter:
The model steps its physics every 50 microseconds and its controller every millisecond, and it is a model: it does not run on silicon, and the mass, spring and damping numbers are illustrative. Real tuning always ends on the machine.
The ODrive tuning guide gives a plain order for the three gains, and it is the order of the cascade, inside out. First set the integral gain to zero and keep the position gain low. Raise the velocity gain by about 30% at a time until the motor shows some vibration, then back it down to 50% of the vibrating value. Next raise the position gain by about 30% at a time until command steps overshoot, then back it down until the overshoot is gone. Last, raise the integral gain until speed changes or disturbances become underdamped, then reduce it to about half. The guide adds that the position gain and the integral gain are both limited by overshoot and may need to be tuned against each other. The guide gives no units and no starting numbers, so the model's numbers are our own.
The order matters because each loop depends on the one below. A good outer gain on a shaky inner loop gives a joint that rings, and no outer gain can repair it. Tune the quickest, innermost loop first, then wrap the next one around it.
The bench below checks four things after each 1 rad move. The joint must settle to within 2% in under 0.4 s. It must overshoot by less than 5%. During the hold, the current command must stay under 0.15 A rms, which means no chatter. And the load must stay within 0.005 rad peak to peak, and finish within 0.01 rad of the target, which means no hunting and no offset. These limits are our own picks for the model, not standards. Use the presets to see the recipe's stages, then tune by hand.
The checks are our own limits for this model. The model: gains and clamps as listed above, 1 kHz controller, 50 microsecond physics step, 1.5 times heavier load, a 1 rad move as a 0.15 s ramp. Everything is illustrative; none of it is a measurement of a real joint.
Step through the presets. Start low is safe and slow: it passes three checks and fails the settle time. Speed gain set raises the speed gain with a low position gain; it still settles slowly and the gap leaves a ripple. Position and integral passes all four. Too hot pairs a coarse encoder with high gains, and the current command chatters at a few amps, because every count of change in the speed estimate is multiplied by the speed gain (Chapter 4). Now break the good tune: open the gap to 0.1, move the encoder to the load, and turn gravity off. Then fix it with the knobs you have.
Symptom: the joint is calm on the bench and rings once it carries its real arm. Measurement: repeat the step test with the real load and with the worst-case load. A load change shifts the inertia, which changes the speed-loop bandwidth in proportion. Fix: leave margin. Tune with the heavy case and check the light one, because a light load makes the same gain a faster loop and may push it into the delay limit.
On real hardware. On an STM32 Nucleo with a motor-driver board and an encoder motor, repeat the recipe: velocity gain first with the integral off, then position, then integral. Log the target, angle and current command at 1 kHz over UART or a debug probe, and fill in the same four checks with your own limits.
Chapter 10
Run three loops at three rates on one core, latch the encoder at a fixed instant, and add checks that stop a bad sensor from driving the motor
So far the loops lived in a model. On a microcontroller they are functions, and someone must call them at the right moments. Picture a kitchen with one cook. The sauce must be stirred every few seconds, the roast turned every few minutes, and the menu checked every hour. The cook does the most urgent job first and returns to the rest when there is time. A Cortex-M core is that cook.
The current loop is the most urgent. It runs once per PWM period, started by an ADC conversion that the timer triggers at the middle of the period. At a 20 kHz PWM, that is every 50 microseconds. The velocity and position loops can run slower. Our model runs them at 1 kHz, one call every 20 current-loop periods. This is a design choice and an illustrative one; real drives pick rates from the bandwidths they need.
A common layout has two interrupts. The ADC end-of-conversion interrupt runs the current loop and has the highest priority. On a Cortex-M a lower priority number means more urgent, so the current loop gets the lowest number. A counter in that interrupt triggers a second, lower-priority interrupt every 20th time. That second interrupt runs the position and velocity code. If the current loop fires while the slow code runs, the hardware pauses the slow code, runs the fast loop, and resumes. See the RTOS lesson and the real-time systems lesson for the general idea, and from vector table to main for how priorities work on Cortex-M.
The velocity estimate is a difference of positions divided by the time between them. If the slow task reads the encoder whenever it happens to run, the time between reads wobbles, and so does the speed. The fix is to read the counter inside the fast interrupt, on the 20th tick, and store the value. The slow task then uses the stored snapshot. The sample instant is exact, even if the task runs late.
That makes one more number matter: the latency between the sample and its effect. The snapshot is taken at tick 0. The slow task finishes some time later, and the new current request waits for the next current-loop period. The total is the age of the loop's information, which Chapter 6 showed adds phase lag.
The top row shows the fast current interrupt, once per PWM period. The lower row shows the 1 kHz speed and position task filling the gaps. Raise the costs until the slow task cannot finish.
A model with invented costs: the fast interrupt takes the same time every period, and the slow task is released every millisecond. Real costs depend on the part, the clock and the code; measure them on the target. Preemption is assumed to be free here; on a Cortex-M core each exception entry and exit costs on the order of a dozen cycles.
At 20 kHz and 12 microseconds per interrupt, the fast loop uses 24% of the core and the 250 microsecond slow task finishes about 330 microseconds after its release. Move to 40 kHz and the fast loop doubles to 48%; the slow task now finishes later. Push the slow task toward 600 microseconds and the core cannot keep up at 40 kHz: the task misses its deadline and the next one starts late. A control loop that runs late looks, to the maths, like a loop with delay.
c, two interrupts: current loop at 20 kHz, velocity and position at 1 kHz void ADC_IRQHandler(void) { /* highest priority, every 50 us */ float i_meas = adc_to_amps(ADC1->JDR1); float v_cmd = pi_step(&cur_pi, i_ref - i_meas); /* Kp = L*wc, Ki = R*wc */ pwm_set_voltage(clampf(v_cmd, -V_BUS, V_BUS)); if (++tick == 20) { tick = 0; enc_snapshot = TIM3->CNT; /* latch the encoder at a fixed instant */ NVIC_SetPendingIRQ(SLOW_IRQn); } } void SLOW_IRQHandler(void) { /* lower priority, every 1 ms */ int32_t pos = unwrap16(enc_snapshot); float theta = pos * RAD_PER_COUNT; float w = velocity_rad_s(pos); /* Chapter 4 */ float w_cmd = clampf(KP * (target - theta) + w_ff, -W_MAX, W_MAX); float e = w_cmd - w; integ = clampf(integ + KI * e * TS, -I_MAX, I_MAX); /* anti-windup: clamp */ i_ref = clampf(KV * e + integ, -I_MAX, I_MAX); /* torque request to the fast loop */ }
Read the data flow in one line each. The fast loop takes an ADC current in amps and returns a PWM voltage. The slow loop takes a counter snapshot and returns a current request i_ref. The only shared variable is i_ref, and a 32-bit float written in one instruction needs no lock on a Cortex-M.
The loops obey the encoder. A wrong encoder value drives the motor wrongly, as fast as the loops allow. So firmware adds checks that run next to the loops. The table lists the common ones.
| Check | What it catches | Action |
|---|---|---|
| CRC on every absolute frame | A bit flipped on the wire (Chapter 3) | Drop the frame, reuse the last good one, count the fault |
| Skipped-state counter | Both quadrature bits changing at once (Chapter 1) | Count it, raise a fault above a rate |
| Jump limit | A position change larger than the top speed allows in one tick | Reject the sample, fault if it repeats |
| Index-to-index count | Lost counts (Chapter 2) | Re-home or flag the position as untrusted |
| Stall check | High current requested while the speed stays near zero | Cut torque |
| Two-encoder cross-check | Motor and load angle disagree by more than the gap plus a margin | Fault, safe stop |
Each fault ends in a defined state. The usual one is to turn the torque off and let a brake hold or the joint coast, depending on the machine. The capstone lesson on a CAN joint controller (fw-mot-03) builds such a safe stop with a deadman timer, and the lesson on fail-safe design (pai-fw-08) covers the wider theory.
On real hardware. On an STM32F4 or G4 Nucleo, set a GPIO high at the entry of the fast interrupt and low at the exit, and watch it on a logic analyzer. Measure the pulse width, which is the cost, and the period, which should be 50 microseconds. Do the same for the slow task. The Cortex-M4 DWT cycle counter gives the same numbers in code.
Chapter 11
Keep the numbers, the checklist, the core code and the sources that this lesson rests on
A joint is only as good as what it can measure. An encoder gives counts, either as two square waves in quadrature or as a serial frame with a CRC. Firmware counts them with a timer, unwraps the counter, and makes a speed with a window that trades noise for delay. Three nested loops use these numbers: a current loop with gains taken from the winding, a velocity loop that treats torque as instant, and a position loop that is one gain. Tune from the inside out. Watch the gap in the gear, and check every sensor read.
| Term or rule | Value | Where it comes from |
|---|---|---|
| Counts per turn at 4x | 4 × PPR (2,048 PPR gives 8,192 counts, 0.044° each) | Wikipedia, incremental encoder: a x4 multiplier counts every state change |
| Sample rate rule | Above the count rate, or counts are lost; a four-step jump is silent | Derived in Chapter 2 from the state table |
| STM32 encoder mode | TIMx_SMCR, SMS = 011 counts both TI1 and TI2; DIR in TIMx_CR1 | ST reference manual RM0351 (STM32L4), timer chapter; the Nucleo-F411RE manual RM0383 has a sibling chapter (not opened) |
| Counter unwrap | pos += (int16_t)(now − last), read often enough to stay under 32,768 counts | Chapter 2 |
| nRF52840 QDEC | SAMPLEPER 128 µs to 131,072 µs; ACC −1,024 to 1,023; double transitions not accumulated | Nordic nRF52840 product specification, QDEC |
| SSI | Clock 100 kHz to 2 MHz; most significant bit first; 90 kbit/s at 1.2 km, 10 Mbit/s at 5 m | Wikipedia, synchronous serial interface |
| BiSS C | RS-422 up to 10 MHz at 1 km; up to 64 bits per slave; CRC; cycle times below 10 µs | Wikipedia, BiSS interface; biss-interface.com |
| Frame age | Clocks ÷ clock rate; position error = speed × frame time | Chapter 3 (worked) |
| Speed step and delay | q ÷ (N × Ts); delay about N × Ts ÷ 2 plus 1 ÷ (2π fc) | Chapter 4 (worked) |
| Current PI | Kp = L · ωc, Ki = R · ωc; keep ωc under about a tenth to a twentieth of the loop rate | Chapter 5; the ratio is a rule of thumb, shown in the model |
| Velocity bandwidth | ωv = Kv · (Kt ÷ J) | Chapter 6 |
| Following error | Speed ÷ position gain, with no feedforward | Chapter 7 |
| Motor-side offset | Half the gap, when gravity holds the load on one side | Chapter 8 (model) |
| Tuning order | Velocity gain up about 30% a try until it vibrates, then to 50%; then position gain; then integral | ODrive tuning guide |
c, the whole cascade in one place (illustrative gains; fast loop shown in Chapter 10) typedef struct { float kp, kv, ki, w_max, i_max, ts; float integ; } joint_t; /* called every 1 ms with the latched count */ float joint_step(joint_t *j, int32_t pos_counts, float target_rad, float w_ff) { float theta = pos_counts * RAD_PER_COUNT; float w = velocity_rad_s(pos_counts); /* window + filter, Chapter 4 */ float w_cmd = clampf(j->kp * (target_rad - theta) + w_ff, -j->w_max, j->w_max); float e = w_cmd - w; j->integ = clampf(j->integ + j->ki * e * j->ts, -j->i_max, j->i_max); return clampf(j->kv * e + j->integ, -j->i_max, j->i_max); /* current request, A */ }
This lesson is the second of the motion track. Before it comes Motors for Firmware People, which explains how the motor makes torque. After it comes the joint capstone, a CAN joint controller, where commands, a deadman timer and torque limits meet over a bus. The inside of the current loop, the Clarke and Park transforms and PWM and ADC timing, belong to the motor-control firmware lesson (pai-fw-06). Other related lessons are CAN and EtherCAT (pai-fw-05) and fail-safe design (pai-fw-08).
For the control theory behind the loops, read trajectory tracking with PID and LQR and control in the navigation series. For better speed estimates, see the Kalman filter. For how joints fit into whole robots, see sensor and actuator integration and real-time performance. For timers, see timers, PWM and sampling, and for logging and tracing, debug, trace and observability.
This lesson has no slides. It was built from these primary and reference sources, opened on 2026-11-01 except where noted:
Not verified against a primary source: the 1/10 to 1/20 bandwidth ratio, the 5 to 10 times loop separation, and the exact BiSS frame layout and CRC polynomial. These are marked as rules of thumb or illustrative in the text. The motor, joint and timing numbers throughout are illustrative model values, not measurements.
Now press Teach and explain one joint out loud, from memory: how A and B give direction, why the sample rate must exceed the count rate, how a window trades noise for delay, why the inner loop must be faster, and what a gap does to a loop that sees it. Then go back to the joint at the top, pick the cascade that is too hot, and say which number in this lesson explains the chatter.