A planned trajectory says where the robot should be at every second. Wind and wheel slip push it off. Replayed blind, the plan is more than a metre off within two laps. With feedback on the error in the robot's own frame, the same robot stays within about 7 cm.
Pick a controller, press Push, and watch the error ruler under the track. Then we build, piece by piece, the error, feedforward plus feedback, PID, a tracking law for wheels that cannot slide, and LQR gains from a cost.
You need sine and cosine and a little Python. We build the rest from zero.
Lesson 6 of 15 in our follow-along of Stanford AA 274A, Principles of Robot Autonomy I. Every idea is re-taught here in our own words and devices. Previous: Lesson 5, Trajectory Optimization. Next: Lesson 7, Sensors.
Illustrative toy. A figure eight 3.2 m wide, one lap in 24 s, speeds 0.28 to 0.59 m/s. Plan + feedback is the tracking law of Chapter 4 with gains 1, 4 and 4. The ruler shows the distance from the robot to the yellow reference point.
Chapter 0
Replay a plan with a one-degree error and watch the miss grow
In Lesson 5 the planner produced a trajectory: a desired pose at every instant, and the wheel commands that produce it. On a perfect robot you could send those commands and walk away.
A real robot is not perfect. Its gyro reads 1° off. One wheel is 1% smaller than the model says. A gust pushes it sideways. Each error is small. The robot never measures them, so they add up.
The plan says: drive straight at 1 m/s for 30 s. Set the robot's heading error, then press Drive. We stretch the side scale so you can see the miss.
Illustrative toy. The robot obeys the planned commands exactly; only its heading is off. The side offset after time t is v × t × sin(heading error).
Work the number. The robot drives 1 m/s for 30 s with a 1° heading error. Its side offset is 30 × sin(1°) = 30 × 0.0175 = 0.52 m. Double the time and the miss doubles. Nothing in the plan can see it.
The fix is trajectory tracking: measure the robot's pose many times a second, compare it with where the plan says it should be, and correct. This is closed-loop control, from Lesson 1, applied to a moving target. The hero shows all three options on one figure eight.
The symptom is a robot that follows the path in simulation and drifts on the floor. To measure it, log the pose error against time; a straight-line growth means an uncorrected bias. The fix is feedback on that error.
Chapter 1
Switch each half off and see what the other half cannot do alone
Start in one dimension. A yellow target slides along a rail at 1 m/s. The robot must stay on it. Call the target's position xd (d for desired) and the robot's position x. The tracking error is desired minus actual: e = xd − x.
The command has two parts. The feedforward is the plan's own command, ud: here, "move at 1 m/s". The feedback is a correction from the measured error. The simplest one multiplies the error by a gain k: how hard to push for each metre of error.
u equals u-d plus k times e.
Send the plan's command u-d. Measure the error e. Add k times e on top, so a robot that is behind speeds up and a robot that is ahead slows down.
With made-up numbers: u-d = 1 m/s, k = 2 per second, and the robot is 0.3 m behind. u = 1 + 2 × 0.3 = 1.6 m/s, so it closes the gap.
The target moves at 1 m/s. Turn feedforward and feedback on or off, set the gain, and press Push to knock the robot 1 m back. The plot is the error over time.
Illustrative toy, simulated at 100 Hz. The dashed curve after a push is the exact decay e(0) × e−kt.
Each half alone fails in its own way. Feedforward alone moves the robot but never removes a push. Feedback alone needs a standing error to make any speed at all. It settles where k × e = 1 m/s, so it lags by 1/k metres. With k = 2 that is 0.5 m behind, forever.
With both, the feedforward carries the robot and the feedback sees only the leftover error. That error then follows a simple rule: it shrinks at a rate proportional to itself.
e of t equals e of zero times e to the minus k t.
Each 1/k seconds, the error e(t) keeps 37% of what it had. A bigger k shrinks it faster. A negative k makes it grow.
With made-up numbers: e(0) = 8 and k = 0.5 per second. After 2 s, e = 8 × 0.368 = 2.94. After 6 s, 0.40. With k = −0.5, after 6 s it is 161.
The symptom is a robot that trails its reference by a steady amount. To measure it, plot the error at constant speed: a flat non-zero line is a missing feedforward. The fix is to add ud, not to raise k.
Chapter 2
Tune three gains on a mass that a load drags down
The rail robot set its speed directly. Most bodies do not: a motor sets a force, so the command changes the acceleration. A mass like this has inertia. A push-proportional-to-error rule makes it swing past the target and back, forever. We need two more terms.
The CMU 16-831 control lesson builds PID from scratch. Here is the short form. Call the error now e, its running total ∫e dt, and its rate of change de/dt. Give each a gain: Kp, Ki and Kd.
u equals K-p times e, plus K-i times the integral of e d-t, plus K-d times d-e by d-t.
Push in proportion to the error e. Add a push that grows while error stays, the integral. Subtract a push when e is falling fast, the derivative. Sum the three into u.
With made-up numbers: K-p = 8, K-d = 4, the error fell from 0.5 to 0.3 m in 0.1 s. P gives 8 × 0.3 = 2.4. D gives 4 × (−2.0) = −8.0. u = −5.6: brake, before the target.
The mass starts at 0 and must reach the yellow line at 1 m. A load pulls it down with 1.2 m/s². Move the gains and read the curve.
Illustrative toy: a unit mass, simulated for 15 s at 1 kHz. Try K-p 8 and K-d 0 (it swings forever), then K-d 4, then K-i 2.
Read the default. With Kp = 6 and no integral, the mass stops where the P push cancels the load: 6 × e = 1.2, so e = 0.2 m. It parks at 0.8 m. Add Ki = 2 and the integral grows until it holds the 1.2 alone. The error goes to zero.
| Term | Looks at | Fixes | Costs |
|---|---|---|---|
| P | the error now | most of the gap | a standing offset under a load |
| I | the error so far | the offset | overshoot, and windup when stuck |
| D | the error's rate | swinging and overshoot | it amplifies sensor noise |
The symptom is a violent overshoot after something held the robot still. To measure it, log the integral term: it is huge. This is integral windup. The fix is to stop adding to the integral while the motor is at its limit (Chapter 9).
Chapter 3
Drag the reference and split the gap into ahead, sideways and heading
A wheeled robot has a pose: position x, y and heading θ (theta), from Lesson 2. The plan gives a reference pose xd, yd, θd. The gap in world coordinates, "0.3 m east, 0.5 m north", does not tell the robot what to do. Its wheels only know forward and turn.
So rotate the gap into the robot's frame. Its first axis points where the robot faces; its second points to the robot's left. Call the gap along the first axis the along-track error ex. Call the gap along the second the cross-track error ey. Call the heading gap the heading error eθ.
e-x equals cos theta times delta-x plus sin theta times delta-y. e-y equals minus sin theta times delta-x plus cos theta times delta-y. e-theta equals theta-d minus theta.
Take the world gap delta-x, delta-y. Turn it backwards by the robot's heading theta. The first part is e-x, the gap ahead; the second is e-y, the gap to the left. Subtract the headings for e-theta.
With made-up numbers: the robot faces north, theta = 90°. The gap is 0.3 m east, 0.5 m north. e-x = 0 × 0.3 + 1 × 0.5 = 0.5 m ahead. e-y = −1 × 0.3 + 0 = −0.3 m, so 0.3 m to the right.
Drag the yellow reference anywhere. Turn the robot with the slider. The blue lines are the gap measured along the robot's forward and left axes.
Grid squares are 0.25 m. Heading is measured from east, counter-clockwise. The heading error is wrapped to the range −180° to 180°.
Now each error has one wheel job. A positive ex says "speed up". A cross-track ey says "turn toward it", because the robot cannot step sideways. A heading error eθ says "turn to match". The world heading θ has gone from the problem; this matters in Chapter 7.
The symptom is a robot that turns the wrong way when heading south. To measure it, log ey with the robot pointed each of four ways: a world-frame bug flips sign at 180°. The fix is the rotation above, and wrapping eθ to ±180°.
Chapter 4
Start the robot off the line and watch it turn in and settle
The unicycle model has two commands: forward speed v and turn rate ω (omega). It moves only where it faces. The plan gives a reference speed vd and turn rate ωd, the feedforward. A cross-track error cannot be fixed directly, so the law fixes it through the heading.
A classic law of this shape is from Kanayama and co-authors (1990). It uses three positive gains: kx for the gap ahead, ky for the gap sideways and kθ for the heading.
v equals v-d times cos e-theta, plus k-x times e-x. Omega equals omega-d plus v-d times the bracket k-y e-y plus k-theta sine e-theta.
Drive at the planned speed v-d, less if the heading is off, plus k-x times the gap ahead. Turn at the planned rate omega-d, plus a turn toward the side gap e-y and toward the reference heading. The turn correction scales with v-d.
With Chapter 3's errors, 0.5 m ahead, 0.3 m right, heading −10°, and v-d = 0.5, omega-d = 0.2, gains 1, 4, 4: v = 0.492 + 0.5 = 0.99 m/s. Omega = 0.2 + 0.5 × (−1.2 − 0.69) = −0.75 rad/s: speed up, turn right.
The yellow reference drives east along the warm line. Pick how the robot starts, set the planned speed, and press Run. The plot below is the cross-track error.
Illustrative toy with gains k-x 1, k-y 4, k-theta 4, simulated at 200 Hz. Settling means the combined error, ahead, side and heading, stays under 5% of its start.
Near the line, the side error and the heading error form a pair. The robot turns at vd(kyey + kθeθ), and the side error changes at vdeθ. With ky = kθ = 4 the pair settles with no overshoot, at a rate of 2vd per second: 1 per second at 0.5 m/s.
The symptom is a robot that spins on the spot at a planned stop. To measure it, log ω when vd is near zero. The fix is the vd factor above; for a stop at a pose, use a parking law (Chapter 5).
Chapter 5
Slow the robot down and watch the flat tracker's turn command blow up
Lesson 5 planned with differential flatness: the whole unicycle motion follows from x(t) and y(t). That gives a second tracker. Let the robot command its acceleration a instead of its speed, with speed V. Then the accelerations of x and y depend on (a, ω) through a 2 by 2 matrix J.
Choose the accelerations you want, w1 for x and w2 for y, with feedforward plus PD feedback on each axis. For example w1 = ẍd + kp(xd − x) + kd(ẋd − ẋ). Then solve for the real commands.
The column a, omega equals J inverse times the column w-one, w-two. J is the matrix: cos theta, minus V sine theta; sine theta, V cos theta.
Decide how you want x and y to accelerate, w-one and w-two. Multiply by J inverse. Out come the acceleration a and turn rate omega that produce them. Dividing by V is hidden inside J inverse.
With made-up numbers: V = 0.5 m/s, theta = 60°, w-one = 0.3, w-two = −0.1. J inverse = [0.5, 0.866; −1.732, 1.0]. a = 0.15 − 0.087 = 0.063 m/s². Omega = −0.520 − 0.1 = −0.62 rad/s.
The PD laws ask for the same w-one = 0.3 and w-two = −0.1. Lower the speed V and the heading, and read the turn rate the robot must make.
Illustrative limit: a turn rate of 1 rad/s. The curve is |ω| = |−w1 sinθ + w2 cosθ| / V.
This is feedback linearization: J−1 cancels the curve in the model, so each axis behaves like a plain mass. The price is the division by V. As V nears zero the turn command grows without bound, so a flat tracker keeps V above a floor.
To stop at a pose, a third route is a parking law in polar coordinates: distance to the goal, and the angle to the goal. It drives slower as the distance shrinks and turns toward the goal first. With the goal 1 m straight to the left, it commands zero speed and a turn of 1.2 × π/2 = 1.88 rad/s for a turn gain of 1.2.
| Route | Error it uses | Breaks when |
|---|---|---|
| Robot-frame law (Ch. 4) | e-x, e-y, e-theta | planned speed is zero |
| Flat tracker | x, y and their rates, world frame | actual speed V is near zero |
| Parking law | distance and angle to the goal | it does not follow a timed path |
The symptom is a flat tracker that jerks wildly at the start of a run. To measure it, log V and ω: V starts at zero. The fix is a speed floor, or the parking law for the slow ends of a path.
Chapter 6
Turn one dial between error and effort, and read the gain it buys
So far we chose gains by hand. The linear quadratic regulator (LQR) chooses them from a statement of what you care about. You write a cost: each second, pay q × e² for error and r × u² for effort. Add it up over all future time. LQR returns the feedback gain with the lowest total cost.
Take the simplest tracking case. The feedforward carries the robot, and the feedback adds an extra speed u = k × e on top. Then the along-track error changes at −u. Call the weight on error q and the weight on effort r. The best gain has a closed form.
k equals the square root of q over r.
Divide the price of error q by the price of effort r. Take the square root. That is the gain k. Only the ratio matters, so doubling both changes nothing.
With made-up weights: q = 1, r = 1 gives k = 1. q = 100 gives k = 10, fast and costly. r = 100 gives k = 0.1, gentle and slow. To fall to 5% within 1 s you need 3/k ≤ 1, so k ≥ 3 and q/r ≥ 9.
The robot starts 1 m behind its reference. Slide the ratio q/r and compare the blue error with the warm effort.
Exact curves: e(t) = e−kt and u(t) = k e−kt, over 5 s. The error price is q and the effort price is r = 1.
The same machinery works for many errors at once. The weights become matrices Q and R, and a matrix equation, the Riccati equation, gives the gains. Take the unicycle near the line at vd = 0.5 m/s, with Q and R set to 1 on the diagonal. LQR returns: extra speed = 1.0 × ex, extra turn = 1.0 × ey + 1.41 × eθ. Chapter 4's hand law, near the line, is 2 ey + 2 eθ: the same shape.
Where does the Riccati equation come from? Run it backward from the end of a short horizon. For a one-step system with q = r = 1, the cost-to-go grows 1, 1.5, 1.6, … and settles at 1.618; the gain settles at 0.618. The CMU 16-831 lesson does this recursion by hand.
The symptom is an LQR robot that twitches and saturates its motors. To measure it, log u against its limit. The fix is a larger r, or smaller Q entries, until the peak effort fits.
Chapter 7
Change the planned speed and turn rate, and watch the best gains move
LQR needs a linear model. The unicycle is not linear, so we use a linearization: the model of small errors near the reference. In the robot frame, one line of it explains most of this chapter. Call the cross-track error ey, the heading error eθ and the planned speed vd.
e-y dot is about v-d times e-theta.
The side gap e-y closes only while the robot is angled at it. It closes at the speed v-d times the angle e-theta. No speed, no change.
With made-up numbers: v-d = 0.5 m/s and the robot is angled 0.1 rad toward the line. The side gap shrinks at 0.5 × 0.1 = 0.05 m/s. At 0.2 m/s, only 0.02 m/s.
So the model changes with vd, and with the planned turn rate ωd, which couples ex and ey. A gain that is best at one speed is not best at another. Gain scheduling solves LQR at many operating points ahead of time and stores the gains in a table. At run time it looks them up from the plan's speed and turn rate.
Set the planned speed and turn rate. The purple bars are the six LQR gains for that point. The plot compares a 0.3 m side error under the gains for 1 m/s straight (dashed) and the scheduled gains (solid).
Q and R are 1 on the diagonal. Gains solved in your browser by running the Riccati equation to steady state; checked against SciPy's solver. The decay is the linear error model.
Work the number. On a straight path the best heading gain is √(1 + 2vd) for these weights: 1.73 at 1 m/s, 1.18 at 0.2 m/s. Run at 0.2 m/s with the 1 m/s gains, and a 0.3 m side error takes 26.0 s to settle. The scheduled gains take 17.5 s.
Push the schedule to every instant and you get time-varying LQR: gains from a Riccati equation run backward along the whole trajectory. A table of a few dozen points is usually enough.
The symptom is a tracker tuned on straights that wobbles in tight turns or crawls back at low speed. To measure it, plot the error against ωd and vd. The fix is a schedule over those two numbers.
Chapter 8
Pick a controller, push the robot, and slow the loop until it breaks
Here is the hero's figure eight with every controller in this lesson. It has two more dials. The gain multiplier scales every feedback gain. The loop rate is how many times a second the controller measures and sends a new command; between ticks the motor holds the last command.
Choose a controller and press Push. Then raise the gain to 4 times and lower the loop rate to 2 Hz. The strip below is the error over the last 20 s.
Illustrative toy. Physics runs at 600 Hz; the controller runs at the loop rate with a zero-order hold. The LQR mode looks up gains for the current planned speed and turn rate, as in Chapter 7. With the hand law, 4× gain at 2 Hz diverges; 8× at 5 Hz does too (checked offline).
| Controller | In wind | After a push | Why (chapter) |
|---|---|---|---|
| Plan only | drifts without limit | keeps the offset | no measurement (0, 1) |
| Feedback only | trails by about vd/kx | recovers, still trailing | needs a standing error (1) |
| Hand law | a small standing offset | recovers in a few seconds | feedforward plus robot-frame feedback (4) |
| Scheduled LQR | a small standing offset | similar, with gains from a cost | LQR on the error model (6, 7) |
The constant wind leaves both trackers a few centimetres off. That is the steady-state error of Chapter 2: these laws have no integral term. An integral on ey removes it, with the windup care of Chapter 9.
Chapter 9
Stretch the time step until a stable gain goes unstable
A real controller runs in a loop. It reads the sensors, computes, sends a command, and holds it until the next tick. Call the time between ticks Δt. For a proportional loop on a speed-controlled robot, one tick changes the error as follows.
e-t-plus-one equals one minus k delta-t, times e-t.
Each tick multiplies the error e-t by one minus k delta-t. If that multiplier is between minus one and one, the error shrinks. So k times delta-t must stay between 0 and 2.
With k = 1 per second: delta-t = 0.5 gives a multiplier of 0.5, smooth decay. Delta-t = 1 gives 0, done in one tick. Delta-t = 1.5 gives −0.5, it rings. Delta-t = 2.5 gives −1.5, it grows.
The gain is fixed at k = 1 per second. Drag the time step and watch the dots: each is the error at one tick. The dashed curve is the continuous decay.
Exact sequence et = (1 − kΔt)t, starting at 1 m.
The same gain that is stable in continuous time fails when the loop is slow. A common rule: run the loop at least 10 times faster than the closed loop's fastest decay rate. The showcase shows it on the unicycle.
Two more limits. Saturation: a motor has a top speed, so it clips a large command. While clipped, an integral term keeps growing. Ten ticks stuck with e = 5 and Δt = 1 give I = 50; with Ki = 0.3 that is a stored push of 15. Anti-windup stops the integral while the motor is clipped.
python def step(self, e, u_max): deriv = (e - self.prev_e) / self.dt; self.prev_e = e u_raw = self.Kp*e + self.Ki*self.I + self.Kd*deriv u = max(-u_max, min(u_max, u_raw)) # clip to the motor limit if u == u_raw: # not clipped: safe to integrate self.I += e * self.dt return u # clipped: the integral is frozen
Last, model predictive control (MPC). At each tick it solves a small optimization over the next N steps, with the limits as hard rules. It applies the first command and solves again next tick. LQR is its special case with no limits and an endless horizon.
The symptom is a controller that worked in simulation and oscillates on the robot. To measure it, log the real loop period, not the planned one. The fix is a faster loop or a lower gain, so kΔt stays well under 2.
Chapter 10
Keep the terms, the numbers, the code and the links in one place
A tracker sends the plan's command and adds feedback on the error. For a wheeled robot, measure the error in the robot's frame: ahead, sideways, heading. Fix the side error through the turn rate, scaled by the planned speed. Pick gains by hand, by LQR, or by a schedule of LQR gains, and check them at the real loop rate.
| Term | Meaning | Number to remember |
|---|---|---|
| Open-loop drift | side miss = v t sin(heading error) | 1° for 30 s at 1 m/s: 0.52 m |
| Feedforward + feedback | u = ud + k e | feedback only lags 1/k: 0.5 m at k = 2 |
| Error decay | e(t) = e(0) e−kt | 37% left after 1/k seconds |
| PID | Kpe + Ki∫e + Kdde/dt | PD offset = load / Kp: 1.2 / 6 = 0.2 m |
| Robot-frame error | ex, ey, eθ | facing north, gap (0.3, 0.5): 0.5 ahead, 0.3 right |
| Unicycle law | v = vdcos eθ + kxex; ω = ωd + vd(kyey + kθsin eθ) | gains 1, 4, 4: side pair decays at 2vd |
| Flat tracker | [a; ω] = J−1[w1; w2] | det J = V; keep V above a floor |
| LQR | k = √(q/r) | 5% in 1 s needs q/r ≥ 9 |
| Gain schedule | LQR gains over vd, ωd | 0.2 m/s: 26.0 s fixed, 17.5 s scheduled |
| Sampling | et+1 = (1 − kΔt) et | stable only for 0 < kΔt < 2 |
python import numpy as np def track(pose, ref, kx=1.0, ky=4.0, kth=4.0): x, y, th = pose # where the robot is xd, yd, thd, vd, wd = ref # where the plan says it is, and its commands dx, dy = xd - x, yd - y # world gap ex = np.cos(th)*dx + np.sin(th)*dy # gap ahead ey = -np.sin(th)*dx + np.cos(th)*dy # gap to the left eth = np.arctan2(np.sin(thd - th), np.cos(thd - th)) # heading gap, wrapped v = vd*np.cos(eth) + kx*ex # feedforward speed + along-track feedback w = wd + vd*(ky*ey + kth*np.sin(eth)) # feedforward turn + side and heading feedback return v, w
Based on Stanford AA 274A, Principles of Robot Autonomy I. This page re-teaches the course's lesson on trajectory tracking in our own words, devices and toy numbers. The tracking law of Chapter 4 is from Kanayama, Kimura, Miyazaki and Noguchi (1990).
Now press Present or Teach and explain from memory: why a plan drifts, feedforward plus feedback, the robot-frame error, the tracking law and the q/r dial. Then go back to the figure eight, pick Feedback only, and say why it trails.