The loop
In "The PID controller" a cart was pushed by u = Kp·e + Ki·∫e dt − Kd·dy/dt. A computer cannot do calculus all the time. It runs a loop: every T seconds read the sensor, work out u, write it, wait.
The ADC (analog-to-digital converter) turns the cart position into a number, but only at the ticks t = kT. That number is the sample y[k]. At tick k = 5, t = 50 ms, it reads y[5] = 0.2733 m.
PID as sums
The error and the proportional part need no change: use the sample in place of y(t). e[5] = 1 − 0.2733 = 0.7267 m, so P = 300 × 0.7267 = 218.0 N.
∫e dt is the area under the error. Each tick adds one thin rectangle, height e[k], width T: the Euler rule from "Discretising a controller: Euler versus Tustin". I goes from 9.2 to 10.7 N.
dy/dt becomes (y[k] − y[k−1]) / T, so the code keeps the last sample. A light low-pass filter tames sensor noise, giving D = a·D − b·(y − y_old). Here D = −149.1 N: it brakes the moving cart.
u = P + I + D = 79.6 N goes to the DAC (digital-to-analog converter). It holds that force steady until the next tick: a zero-order hold. So the force is a staircase, one stair per tick.
Every formula assumed the ticks are exactly T apart. So wait for a fixed deadline, not for sleep(T) after the work: then the time the code itself takes does not stretch the period.
Choosing T
With T = 10 ms the sampled loop follows the analog controller closely. On a 1 m move the two positions never differ by more than 5.4 cm, and neither overshoots (0.0 % and 0.0 %).
Same gains, T = 50 ms. Each force is held five times longer, so on average it acts later. The loop loses damping and the cart overshoots 12.9 %. Look at the coarse stairs.
At T = 80 ms the same code makes the swing grow: about 2.0 m off target in the second second, 37 m by the sixth. Sampling too slowly can make a stable design unstable. Pick T small against the loop's speed.
What is happening
# step 1/10 · loop # about: Timer: every T, ADC: read y, PID code, DAC: write, hold u, Cart (plant) the cart y'' + 10 y' + 20 y = u command r = 1 m (a step) gains Kp = 300, Ki = 200, Kd = 20 the loop, once every T seconds: read y (sensor → ADC → number) compute u (a few lines of Python) write u (number → DAC → force) wait for the next tick We take T = 10 ms: 100 passes a second.
The cart and the gains are the ones from "The PID controller": 1 kg, 10 N·s/m, 20 N/m, Kp = 300, Ki = 200, Kd = 20. Every curve and number in the figure is simulated from the sampled loop, with the cart moved forward in 10-microsecond steps between ticks. adc.read, dac.write and wait_tick stand for whatever your hardware library provides. The Python on the last steps is plain Python 3 and prints the overshoot the figure shows.