Inverted Pendulum Simulation: PID vs LQR

Compare PID and LQR on a nonlinear cart–pole with actuator saturation. Play the motion, apply timed pushes, and inspect settling, cart travel and closed-loop poles.

#inverted-pendulum #LQR #nonlinear-dynamics #ode45 #PID

This inverted pendulum simulation compares two ways to balance a rigid pendulum on a moving cart. It is designed for control engineering students, teachers preparing a lab, and engineers exploring the difference between angle regulation and control of the whole mechanical state. Both controllers act on the same nonlinear cart–pole, with the same starting state, force limit and recorded pushes.

Start with the Michigan tutorial parameters already entered. Press play to watch the selected controller, or scrub Playback time to inspect a particular instant. The charts always compare both controllers. While playback runs, Space or a tap on the drawing adds a horizontal impulse at the pendulum’s centre of mass. The recorded push schedule is replayed for each controller. A positive impulse acts to the right. Drag the blue initial-angle handle to change the starting tilt; it represents the initial pose rather than the current simulated pose.

For the LQR inverted pendulum, adjust the four diagonal Q weights and the R control-effort weight. The calculator solves the continuous algebraic Riccati equation again for the entered plant. It does not substitute a stored gain vector. Weights apply to numerical SI states in the order cart position, cart velocity, angle in radians and angular velocity in radians per second. Changing the display to US units does not change this design convention.

For cart pole PID, begin with the tutorial angle gains. Angle-only feedback can regulate tilt while allowing the cart to drift. Enable the optional cart position loop to generate a bounded tilt command from cart displacement and velocity. The inner PID differentiates measured angle and freezes its integrator when integration would drive the force farther into saturation. The outer loop needs its own tuning; enabling it does not guarantee recovery.

Read the two balance outcomes alongside peak force and settling times. Settling is measured from simulation start, after the last scheduled push, using the entered absolute angle and position bands. A reported time requires at least half a second of subsequent observations inside the band. “No value” means settling was not established before the simulation ended or a limit was reached. The pole tables describe the unsaturated linear model at upright, so stable poles alone cannot predict recovery from a large tilt.

This inverted pendulum calculator includes rigid-body inertia, gravity, cart friction and force saturation. It omits motor electrical dynamics, delays, sensor noise, flexibility, backlash and collisions with stops. Each run ends at horizontal pole angle or the cart travel limit; no impact or swing-up motion is inferred. Use it for learning, controller comparison and preliminary investigation before a physical experiment.

How it is calculated

The nonlinear equations use the CTMS upright angle convention: ϕ>0\phi>0 leans left and x>0x>0 points right. Write J=Icm+mℓ2J=I_{cm}+m\ell^2, c=mℓcos⁡ϕc=m\ell\cos\phi and D=(M+m)J−c2D=(M+m)J-c^2. The coupled rigid-body equations are

[M+m−c−cJ][x¨ϕ¨]=[u−bx˙−mℓsin⁡ϕ ϕ˙2mgℓsin⁡ϕ].\begin{bmatrix}M+m&-c\\-c&J\end{bmatrix}\begin{bmatrix}\ddot x\\\ddot\phi\end{bmatrix}=\begin{bmatrix}u-b\dot x-m\ell\sin\phi\,\dot\phi^2\\mg\ell\sin\phi\end{bmatrix}.

The explicit inverse of this positive mass matrix supplies the nonlinear derivatives. The upright linearization uses state order [x,x˙,ϕ,ϕ˙][x,\dot x,\phi,\dot\phi] and the CTMS A and B matrices. Numeric SI bases make the mixed state units explicit.

LQR minimizes ∫0∞(zTQz+Ru2) dt\int_0^\infty(z^TQz+Ru^2)\,dt. A scaled matrix-sign iteration on the Hamiltonian obtains the stabilizing solution of ATP+PA−PBR−1BTP+Q=0A^TP+PA-PBR^{-1}B^TP+Q=0; K=R−1BTPK=R^{-1}B^TP and uc=−Kzu_c=-Kz. The Riccati residual and published tutorial gains are checked.

PID uses e=ϕ−ϕre=\phi-\phi_r and uc=−Kpe−Kdϕ˙−Ki∫e dtu_c=-K_pe-K_d\dot\phi-K_i\int e\,dt. With the optional outer loop, ϕr=clip(Gxx+Gvx˙,±ϕr,max)\phi_r=\mathrm{clip}(G_xx+G_v\dot x,\pm\phi_{r,max}). Conditional integration prevents further windup under saturation. Both controllers apply u=clip(uc,±Flimit)u=\mathrm{clip}(u_c,\pm F_{limit}).

Adaptive Dormand–Prince ode45 integrates each controller independently, with relative tolerance 10⁻⁶ and requested samples no more than 0.01 s apart. It restarts at each integration-span boundary and exactly at every recorded push. Cached baseline samples only seed a restart before the first push; ode45 advances the remaining fraction to the push time. A rightward impulse JpJ_p at the COM gives Δx˙=(Icm+mℓ2sin⁡2ϕ)Jp/D\Delta\dot x=(I_{cm}+m\ell^2\sin^2\phi)J_p/D and Δϕ˙=−Mℓcos⁡ϕ Jp/D\Delta\dot\phi=-M\ell\cos\phi\,J_p/D. Mechanical energy includes translational, rotational and coupling terms; actuator work, impulse energy and viscous loss close the energy balance.

Assumptions

Planar rigid pendulum with independent centroidal inertia; frictionless pivot; viscous cart friction; ideal continuous full-state measurements; zero position target; direct force actuator with a symmetric limit. The initial angle and angular velocity are converted to radians for dynamics. The bob marker locates the centre of mass a distance ℓ from the pivot; its drawn radius and the cart artwork do not prescribe inertia or collision geometry.

The default masses, length, friction, inertia and gravity follow the CTMS executable examples. The older modeling page's introductory table says m = 0.5 kg, but its code, numerical matrices and LQR example consistently use m = 0.2 kg; this tool follows the latter. PID outer-loop defaults are illustrative tuning choices, not published tutorial gains.

Where it applies

Balance control only: simulation stops on the first |φ| = 90° or |x| = cart travel limit, with no collision, bounce or swing-up model. A stop at the travel limit is reported separately from a fallen pole. Initial |φ| ≤ 60° is an input range, not a guaranteed region of attraction. Riccati and pole results apply to the local unsaturated upright model; rail stops, force limits and the outer tilt-command limit can dominate nonlinear behavior.

Settling is the first sampled time after the last in-window push from which the relevant absolute bands remain satisfied to the end, with at least 0.5 s confirmation. Times are absolute simulation times, not elapsed times after a push. “No value” in a settling result means settling was not established. Peak force is sampled at ≤ 0.01 s intervals; a brief internal peak can be under-resolved when it does not reach the force limit. Halve Maximum integration span to check convergence; adaptive solver tolerances remain fixed.

The animation interpolates the solved position and angle with shape-preserving cubic interpolation, and force linearly. It freezes each controller at its own stopping event. The fading trail spans the preceding 0.8 s. Pole tables include the PID integral state when Ki > 0; angle-only control retains uncontrolled cart modes. Near-zero poles may be rounded by the eigensolver. Results do not include motor voltage/current dynamics, digital sampling, delay, noise, dry friction, flexibility or parameter uncertainty.

Undisturbed trajectories are cached. At the first recorded push, integration resumes from the preceding saved baseline state and advances to the exact push time before applying the impulse. Subsequent pushes likewise split the nonlinear integration exactly. Playback stops when a physical angle or travel limit is reached.

Supported numerical range. This explicit ode45 implementation accepts settings for which simulation duration multiplied by the largest upright closed-loop pole magnitude, across both PID and LQR, is at most 2000. This conservative computational budget is a numerical support limit, not a stability or safety boundary. The budget is checked before any integration; unsupported settings produce an input error and no trajectory or performance results. Reduce controller gains or duration, or increase cart mass, pendulum length or centroidal inertia. Supported runs retain the full nonlinear equations, adaptive tolerance and ≤ 0.01 s output sampling.

The fixed scene viewport covers the full pendulum reach beyond both cart limits, the bob outline and a 14 px handle grab target. Its bounds depend only on cart travel and pendulum length, so dragging the initial tilt or position does not move the ground or rescale the scene.

References

  • University of Michigan and Carnegie Mellon University, Control Tutorials for MATLAB: Inverted Pendulum, state-space design. Published baseline and tuned LQR gains and open-loop poles. https://www2.ensc.sfu.ca/people/faculty/saif/ctm/examples/pend/invSS.html
  • University of Michigan and Carnegie Mellon University, Control Tutorials for MATLAB: Inverted Pendulum, PID control. Angle gains Kp = 100, Ki = 1, Kd = 20 and cart-drift example. https://www2.ensc.sfu.ca/people/faculty/saif/ctm/examples/pend/invPID.html
  • CTMS Inverted Pendulum: System Modeling, nonlinear equations and upright state-space model. https://ctms.engin.umich.edu/CTMS/index.php?example=InvertedPendulum&section=SystemModeling
  • Åström, K. J. and Murray, R. M., Feedback Systems: An Introduction for Scientists and Engineers, 2nd ed. (2021), state feedback and PID. Open electronic edition and companion material: https://fbsbook.org/

Inputs

InputSymbolUnitDefault
Animate controllercontrollerLQR
Playback time
Play, then press Space or tap the scene to push the pendulum.
ts0.22
Simulation durationT_runs5
Initial tilt
Positive tilt leans left of upright.
theta0deg15
Initial cart positionx0m0
Initial cart velocityv0m/s0
Initial angular velocityomega0deg/s0
Push times
Space or a scene tap adds the entered impulse at the centre of mass.
pushes3.2
Pendulum push impulseJ_pushN*s0.035
Cart massM_cartkg0.5
Pendulum massm_polekg0.2
Pivot to centre of massellm0.3
Pendulum inertia at centre of massI_cmkg*m^20.006
Cart viscous frictionb_cartN*s/m0.1
Gravitational accelerationg_accm/s^29.8
Cart travel each side
Travel limit applies to the cart centre; the run ends at either limit.
railm0.5
Actuator force limitF_limitN12
Q: cart positionq_x5000
Q: cart velocityq_v0
Q: angleq_theta100
Q: angular velocityq_omega0
R: control effort
Weights apply to numerical states in m, m/s, rad, rad/s and force in N.
r_force1
Angle proportional gainK_pN/rad100
Angle integral gainK_iN/(rad*s)1
Angle derivative gainK_dN*s/rad20
PID cart position loopposition_loopfalse
Position to tilt gainG_xrad/m0.7
Velocity to tilt gainG_vrad*s/m0.38
Tilt command limittheta_ref_maxdeg12
Maximum integration span
Each span restarts adaptive ode45; halve it to check numerical convergence.
h_maxs0.2
Angle settling bandtheta_banddeg1
Position settling bandx_bandm0.01

Results

With the default inputs above, the calc gives:

ResultValue
LQR balance outcomeWithin travel and upright limits
PID balance outcomeCart reached travel limit
LQR peak absolute force12 N
PID peak absolute force12 N
LQR angle settling time3.63 s
LQR angle and cart settling time3.85 s
LQR simulated until5 s
PID simulated until0.879 s

It also shows: PID angle settling time, s; PID angle and cart settling time, s.

Checked against sources

Each case below was calculated by this calc and agrees with the value from its source (within the tolerance where one is shown).

CTMS baseline LQR gains

Source: University of Michigan/Carnegie Mellon Control Tutorials, state-space inverted pendulum, LQR design: Q = diag(1,0,1,0), R = 1. Published K = [-1.0000 -1.6567 18.6854 3.4594]. https://www2.ensc.sfu.ca/people/faculty/saif/ctm/examples/pend/invSS.html

Inputs: Q: cart position = 1; Q: angle = 1; the others as above.

ResultSourceThis calc
LQR state feedback gains [1]-1-1
LQR state feedback gains [2]-1.657-1.657
LQR state feedback gains [3]18.68518.685
LQR state feedback gains [4]3.4593.459

CTMS tuned LQR gains

Source: University of Michigan/Carnegie Mellon Control Tutorials, state-space inverted pendulum, LQR design: Q = diag(5000,0,100,0), R = 1. Published K = [-70.7107 -37.8345 105.5298 20.9238]. https://www2.ensc.sfu.ca/people/faculty/saif/ctm/examples/pend/invSS.html

Inputs: the default inputs above.

ResultSourceThis calc
LQR state feedback gains [1]-70.711-70.711
LQR state feedback gains [2]-37.835-37.834
LQR state feedback gains [3]105.5105.5
LQR state feedback gains [4]20.92420.924

CTMS open-loop instability

Source: CTMS state-space inverted pendulum, open-loop poles: 0, -0.1428, 5.5651, -5.6041. https://www2.ensc.sfu.ca/people/faculty/saif/ctm/examples/pend/invSS.html

Inputs: the default inputs above.

ResultSourceThis calc
Most unstable open-loop pole5.565 1/s5.565 1/s

Related Resources

Responses

Your email address will not be published. Required fields are marked *

L ading...