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.
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: leans left and points right. Write , and . The coupled rigid-body equations are
The explicit inverse of this positive mass matrix supplies the nonlinear derivatives. The upright linearization uses state order and the CTMS A and B matrices. Numeric SI bases make the mixed state units explicit.
LQR minimizes . A scaled matrix-sign iteration on the Hamiltonian obtains the stabilizing solution of ; and . The Riccati residual and published tutorial gains are checked.
PID uses and . With the optional outer loop, . Conditional integration prevents further windup under saturation. Both controllers apply .
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 at the COM gives and . 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§ion=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
| Input | Symbol | Unit | Default |
|---|---|---|---|
| Animate controller | controller | LQR | |
| Playback time Play, then press Space or tap the scene to push the pendulum. | t | s | 0.22 |
| Simulation duration | T_run | s | 5 |
| Initial tilt Positive tilt leans left of upright. | theta0 | deg | 15 |
| Initial cart position | x0 | m | 0 |
| Initial cart velocity | v0 | m/s | 0 |
| Initial angular velocity | omega0 | deg/s | 0 |
| Push times Space or a scene tap adds the entered impulse at the centre of mass. | pushes | 3.2 | |
| Pendulum push impulse | J_push | N*s | 0.035 |
| Cart mass | M_cart | kg | 0.5 |
| Pendulum mass | m_pole | kg | 0.2 |
| Pivot to centre of mass | ell | m | 0.3 |
| Pendulum inertia at centre of mass | I_cm | kg*m^2 | 0.006 |
| Cart viscous friction | b_cart | N*s/m | 0.1 |
| Gravitational acceleration | g_acc | m/s^2 | 9.8 |
| Cart travel each side Travel limit applies to the cart centre; the run ends at either limit. | rail | m | 0.5 |
| Actuator force limit | F_limit | N | 12 |
| Q: cart position | q_x | 5000 | |
| Q: cart velocity | q_v | 0 | |
| Q: angle | q_theta | 100 | |
| Q: angular velocity | q_omega | 0 | |
| R: control effort Weights apply to numerical states in m, m/s, rad, rad/s and force in N. | r_force | 1 | |
| Angle proportional gain | K_p | N/rad | 100 |
| Angle integral gain | K_i | N/(rad*s) | 1 |
| Angle derivative gain | K_d | N*s/rad | 20 |
| PID cart position loop | position_loop | false | |
| Position to tilt gain | G_x | rad/m | 0.7 |
| Velocity to tilt gain | G_v | rad*s/m | 0.38 |
| Tilt command limit | theta_ref_max | deg | 12 |
| Maximum integration span Each span restarts adaptive ode45; halve it to check numerical convergence. | h_max | s | 0.2 |
| Angle settling band | theta_band | deg | 1 |
| Position settling band | x_band | m | 0.01 |
Results
With the default inputs above, the calc gives:
| Result | Value |
|---|---|
| LQR balance outcome | Within travel and upright limits |
| PID balance outcome | Cart reached travel limit |
| LQR peak absolute force | 12 N |
| PID peak absolute force | 12 N |
| LQR angle settling time | 3.63 s |
| LQR angle and cart settling time | 3.85 s |
| LQR simulated until | 5 s |
| PID simulated until | 0.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.
| Result | Source | This calc |
|---|---|---|
| LQR state feedback gains [1] | -1 | -1 |
| LQR state feedback gains [2] | -1.657 | -1.657 |
| LQR state feedback gains [3] | 18.685 | 18.685 |
| LQR state feedback gains [4] | 3.459 | 3.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.
| Result | Source | This 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.5 | 105.5 |
| LQR state feedback gains [4] | 20.924 | 20.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.
| Result | Source | This calc |
|---|---|---|
| Most unstable open-loop pole | 5.565 1/s | 5.565 1/s |

Responses