Foundations to FrontierPart VII: Applied mathematics and computationBezhig

T04: Embedded software, robotics, feedback, and state estimation

5 exercises, each with a complete solution. 1 figure. 1 code listing.

On this page
  1. A. Prerequisites and observable goals
  2. B. The central question: can software act correctly at the required time?
  3. C. Coordinates and a small kinematic model
  4. D. Feedback compares a target with a measurement
  5. E. Saturation, faults, and estimation
  6. F. Worked simulation and its limits
  7. G. Independent practice
  8. H. Complete solutions: T04
  9. I. Retention and readiness

A. Prerequisites and observable goals#

Before

A01 coordinate transforms; A03 noise; A06 ODEs and numerical stability; C09–C10 timing and concurrency.

After

Analyze a sampled feedback loop, implement a simulated PID controller with saturation, derive a scalar estimation update, and distinguish simulation evidence from real-time or safety validation.

Level: Advanced-entry track. Simulated plants only; no real vehicle, robot, aircraft, or medical-device control.

B. The central question: can software act correctly at the required time?#

Embedded software interacts with limited memory, power, sensors, actuators, and timing constraints. A correct value arriving after its deadline may be useless. A hard real-time requirement treats missing a deadline as an unacceptable system failure under its specification; a soft real-time system tolerates some misses with degraded quality. Neither label follows from using C++ or an operating system marketed for real-time work.

Worst-case execution time, interrupt handling, scheduling, blocking, and communication all affect response bounds. An average loop time or a million successful runs does not prove a deadline is always met. Dynamic allocation, locks, page faults, and unbounded input can complicate timing analysis. Prioritize bounded behavior and an explicit fault response before micro-optimizing arithmetic.

A sensor measurement is not the state itself. It may contain noise, bias, delay, quantization, dropped samples, or an incorrect coordinate frame. Units and timestamps belong in the interface contract. A distance in centimeters interpreted as meters can produce a much larger error than an ordinary numerical integration approximation.

A value that arrives late is wrong. A task is released every 10 ms (blue arrows) and must finish before its next release. The first two jobs finish in time, even though the second starts late. The third overruns its deadline by 1.5 ms (red), and that delays the fourth. For a hard real-time task that one miss is a failure, however correct the computed value.

C. Coordinates and a small kinematic model#

A planar rotation by angle θ\theta maps a body-frame vector into a world-frame vector using

R(θ)=(cos⁡θ−sin⁡θsin⁡θcos⁡θ).R(\theta)=\begin{pmatrix}\cos\theta&-\sin\theta\\\sin\theta&\cos\theta\end{pmatrix}.

For a robot moving forward at speed vv with heading θ\theta and angular speed ω\omega, a basic kinematic model is

x˙=vcos⁡θ,y˙=vsin⁡θ,θ˙=ω.\dot x=v\cos\theta,\qquad \dot y=v\sin\theta,\qquad\dot\theta=\omega.

This model omits slip, dynamics, actuator limits, and many physical details. For a differential-drive idealization with wheel linear speeds vR,vLv_R,v_L and track width b>0b>0, v=(vR+vL)/2v=(v_R+v_L)/2 and ω=(vR−vL)/b\omega=(v_R-v_L)/b. The units check: speed divided by length gives inverse seconds, consistent with angular rate in radians per second.

A transformation’s direction matters. A matrix mapping body coordinates to world coordinates cannot be used unchanged for the reverse map; for a pure rotation, the inverse is its transpose. State-estimation and control failures often originate in such representation errors rather than in sophisticated algorithms.

D. Feedback compares a target with a measurement#

For target rr, measured output ymy_m, and error e=r−yme=r-y_m, a continuous PID form is

u=KPe+KI∫e  dt+KD de dt.u=K_Pe+K_I\int e\,\dd t+K_D\frac{\dd e}{\dd t}.

Proportional action responds to current error. Integral action accumulates persistent error. Derivative action responds to change and is sensitive to measurement noise. Gains have units determined by the plant and signal definitions; arbitrary copied gains are not universally meaningful.

Our plant is the nondimensional first-order system y˙=−y+u\dot y=-y+u, with target 11 and actuator range [−2,2][-2,2]. For constant uu, its exact solution is y(t)=u+(y(0)−u)e−ty(t)=u+(y(0)-u)e^{-t}, giving an analytic check independent of the controller. The simulator uses forward Euler:

yk+1=yk+Δt(−yk+uk).y_{k+1}=y_k+\Delta t(-y_k+u_k).

With constant uu, the deviation from equilibrium is multiplied by 1−Δt1-\Delta t, so numerical decay is stable only when ∣1−Δt∣<1|1-\Delta t|<1, or 0<Δt<20<\Delta t<2. Closed-loop dynamics introduce additional conditions; a stable open-loop discretization does not automatically make arbitrary PID gains stable.

At each sample, the reference computes error from the latest measurement, forms a raw control using the previously accumulated integral, clamps the control, conditionally updates the integral, and advances the plant. This ordering is part of its discrete controller definition. Other discretizations can be reasonable but are not identical implementations of one universal formula.

E. Saturation, faults, and estimation#

Integral windup occurs when the integral continues growing while the actuator cannot provide the requested effort. After the error changes, the accumulated term may keep the actuator saturated in an unhelpful direction. The lab uses conditional integration: do not accumulate farther into saturation, but allow accumulation that helps leave it. This is one simple anti-windup strategy, not a universal controller design.

A dropped measurement is simulated by holding the last measurement. That makes the controller act on stale information. The policy is visible and testable but is not necessarily safe for a real plant. A real system needs freshness limits, fault detection, and a defined safe state. Noise is simulated by seeded Gaussian samples; real sensors may have non-Gaussian errors, bias, correlated drift, or adversarial interference.

For a scalar prior estimate x^\hat x with error variance PP and independent unbiased measurement z=x+νz=x+\nu with variance R>0R>0, consider

x^+=x^+K(z−x^).\hat x^+=\hat x+K(z-\hat x).

The posterior error variance is (1−K)2P+K2R(1-K)^2P+K^2R under the independence assumptions. Differentiate with respect to KK and set the result to zero:

−2(1−K)P+2KR=0⟹K=PP+R,P+=(1−K)P.-2(1-K)P+2KR=0 \quad\Longrightarrow\quad K=\frac{P}{P+R},\qquad P^+=(1-K)P.

A noisy measurement gets less weight. A dynamic Kalman filter also predicts state and uncertainty through a model, often adding process noise QQ before measurement update. The lab implements only this scalar measurement update; it is not a complete robotics state estimator.

F. Worked simulation and its limits#

With KP=2K_P=2, KI=1K_I=1, KD=0K_D=0, Δt=0.01\Delta t=0.01, and 1000 steps, the reference run ended at time 1010 with y≈0.9939814y\approx0.9939814 and u≈0.9962661u\approx0.9962661. A second run with noise standard deviation 0.050.05, seed 1717, and every seventh measurement dropped ended at y≈0.9957102y\approx0.9957102. The slightly closer final value in the noisy run does not prove noise improves the controller; a single final sample is not a complete performance metric.

Inspect the whole trajectory, maximum error, settling behavior, saturation duration, and response under multiple fault patterns. Compare time-step refinements and analytic cases. A controller can look smooth while using the wrong units or hiding a delayed instability. None of these simulated tests establishes a real actuator’s safe operating envelope, worst-case timing, sensor calibration, or regulatory qualification.

G. Independent practice#

F foundation C standard course work T transfer S optional stretch L runnable lab or project. Attempt the complete set before opening its solutions.

T04.01CSolution

For ideal differential drive with vR=0.6v_R=0.6 m/s, vL=0.2v_L=0.2 m/s, and b=0.4b=0.4 m, compute forward speed and angular speed. At heading π/2\pi/2, compute the model’s instantaneous world-coordinate velocity.

T04.02CSolution

For y˙=−y+u\dot y=-y+u with constant u=1u=1, y(0)=0y(0)=0, and Euler step 0.10.1, compute the first two updates and compare the second with the exact value at t=0.2t=0.2.

T04.03TSolution

Explain integral windup for an actuator limited to [−2,2][-2,2]. Why can clamping the output without changing the integral update leave a problem? Propose a fault response for measurements that remain stale beyond a stated limit, without pretending the same response is safe for every plant.

T04.04CSolution

For prior mean 00, variance 44, measurement 33, and measurement-noise variance 11, compute the scalar gain, posterior mean, and posterior variance. State the assumptions behind interpreting that variance.

T04.05LabSolution

Implement starters/control_lab.py: the sampled PID simulation with saturation, conditional integration, seeded measurement noise, periodic dropped measurements, and scalar estimation update. Run tests, reproduce the default trajectory, and compare a noisy/dropout trajectory. Keep every test simulated.

Optional small hints

For T04.01, rotate the forward velocity into the world frame. For T04.03, distinguish the raw requested control from the saturated applied control. For T04.04, derive KK from the variance expression rather than guessing a weight.

H. Complete solutions: T04#

Compare the first step where your work differs. A corrected answer is not yet an independent success.

T04.01Show solution

Units and orientation make the kinematics interpretable

Forward speed is (0.6+0.2)/2=0.4(0.6+0.2)/2=0.4 m/s. Angular speed is (0.6−0.2)/0.4=1(0.6-0.2)/0.4=1 rad/s. At heading π/2\pi/2, x˙=0.4cos⁡(π/2)=0\dot x=0.4\cos(\pi/2)=0 and y˙=0.4sin⁡(π/2)=0.4\dot y=0.4\sin(\pi/2)=0.4 m/s. These values describe an ideal no-slip kinematic model. They do not include acceleration limits or prove a real robot will follow that trajectory.

Back to T04.01
T04.02Show solution

Compare numerical and analytic state

The first update is y1=0+0.1(1−0)=0.1y_1=0+0.1(1-0)=0.1. The second is y2=0.1+0.1(1−0.1)=0.19y_2=0.1+0.1(1-0.1)=0.19. The exact state is 1−e−0.2≈0.1812691-e^{-0.2}\approx0.181269, so Euler overestimates by about 0.0087310.008731. The difference is numerical error for the specified plant and constant input; it is not evidence of sensor noise. A smaller step should reduce the error in the stable regime.

Back to T04.02
T04.03Show solution

An internal state can grow while output is capped

If positive error persists while raw control exceeds 22, accumulating its integral keeps increasing the controller’s request even though the actuator cannot respond further. When the plant approaches or overshoots the target, the stored integral may still force excessive positive effort. Clamping only the output does not remove this stored state. Conditional integration or another anti-windup design addresses the internal accumulation. A stale-sensor policy might stop issuing new motion commands and enter a controlled safe mode after a deadline, but the safe action depends on plant dynamics and hazards; abruptly setting all outputs to zero is not universally safe.

Back to T04.03
T04.04Show solution

Combine estimates according to uncertainty

K=4/(4+1)=0.8K=4/(4+1)=0.8. The posterior mean is 0+0.8(3−0)=2.40+0.8(3-0)=2.4, and posterior variance is (1−0.8)4=0.8(1-0.8)4=0.8. The formula assumes the prior error and measurement noise are unbiased, independent, and have the stated variances, with a direct scalar observation of the same state. Bias, correlation, or a wrong model can make the reported variance overconfident. A small computed variance is not a substitute for checking those assumptions.

Back to T04.04
T04.05Show solution

Complete simulated control laboratory

The code separates measurement, error calculation, raw control, saturation, integral update, and plant update so their order can be traced. The default experiment is deterministic for the stated seed and environment. Tests bound outputs and check selected expected behavior; they do not establish general closed-loop stability or real-time safety.

code/solutions/control_lab.pyPython
"""T04.05: simulated PID on y'=-y+u; no real actuator connections."""
import math
import random

def simulate(kp=2.0, ki=1.0, kd=0.0, dt=0.01, steps=1000,
             noise=0.0, seed=17, drop_every=0):
    if type(steps) is not int or steps < 1 or dt <= 0 or noise < 0:
        raise ValueError("invalid simulation settings")
    if any(not math.isfinite(x) for x in (kp, ki, kd, dt, noise)):
        raise ValueError("finite settings required")
    if type(drop_every) is not int or drop_every < 0:
        raise ValueError("nonnegative fault interval required")
    rng = random.Random(seed)
    y = integral = last_measurement = 0.0
    previous_error = 1.0
    data = []
    for k in range(steps):
        if not drop_every or (k + 1) % drop_every:
            last_measurement = y + rng.gauss(0.0, noise)
        error = 1.0 - last_measurement
        derivative = (error - previous_error) / dt
        raw = kp * error + ki * integral + kd * derivative
        u = max(-2.0, min(2.0, raw))
        # Conditional integration: do not accumulate farther into saturation.
        if abs(raw) <= 2.0 or (raw > 2.0 and error < 0) or (raw < -2.0 and error > 0):
            integral += error * dt
        y += dt * (-y + u)
        if any(not math.isfinite(x) for x in (y, integral, u)):
            raise ArithmeticError("nonfinite simulated state")
        previous_error = error
        data.append(((k + 1) * dt, y, u))
    return data

def scalar_update(mean, variance, measurement, noise_variance):
    if any(not math.isfinite(x) for x in (mean, variance, measurement, noise_variance)):
        raise ValueError("finite measurement and state required")
    if variance < 0 or noise_variance <= 0:
        raise ValueError("valid positive measurement noise required")
    gain = variance / (variance + noise_variance)
    return (mean + gain * (measurement - mean), (1 - gain) * variance)

if __name__ == "__main__":
    print("final (time, state, control):", simulate()[-1])
    print("posterior (mean, variance):", scalar_update(0., 1., 2., 1.))
Back to T04.05

I. Retention and readiness#

Retrieve coordinate transformations, Euler stability, and conditional probability assumptions. Readiness requires identifying units, timing boundaries, saturation, and stale-state behavior in a new control problem. Continue with signals and systems, differential equations, linear control, embedded hardware interfaces, real-time scheduling, and supervised hardware-in-the-loop validation before controlling physical equipment.