Sign In / Join Cloud 360
Engineering • Innovation • Learning
Control Systems & Robotics Advanced 25 min

Closed-Loop Discrete PID Control & Inverted Pendulum Balancing

Design, derive, and implement a discrete-time PID controller with anti-windup clamping to balance a real-time inverted pendulum.

2. Prerequisites & Background Theory:

Continuous-time Laplace transforms, state-space representations, linearized dynamics, and ANSI C microcontroller pointers.

STEP 1

Goal & Engineering Objectives

Stabilize a two-wheeled inverted pendulum mechanism at its inherently unstable vertical equilibrium position ($\theta = 0$). Maintain robustness against continuous external torque impulses while preventing actuator saturation windup.

STEP 2

Governing Mathematical Formulation & Physics

Linearized Inverted Pendulum Equations of Motion: $$\ddot{\theta}(t) = \frac{g}{L} \sin(\theta) - \frac{1}{M L^2} u(t)$$ Near the vertical operating point ($\theta \approx 0$, where $\sin\theta \approx \theta$): $$\ddot{\theta}(t) - \frac{g}{L}\theta(t) = -\frac{1}{M L^2} u(t)$$ In the discrete domain with sample period $T_s = 10\text{ ms}$ ($100\text{ Hz}$): $$u[k] = K_p e[k] + K_i \sum_{j=0}^{k} e[j] T_s + K_d \frac{e[k] - e[k-1]}{T_s}$$ To eliminate 'derivative kick' during setpoint changes, differentiate the process variable $y[k]$ directly instead of the error signal.
STEP 3

System Architecture & Block Flow Diagram

Sensor Fusion Pipeline:
[MPU-6050 6-DOF IMU] --(I2C Fast Mode 400kHz)--> [STM32F401 ARM Cortex-M4]
       |
       v
[Complementary Filter (100 Hz)] --> [Discrete PID with Anti-Windup Clamping]
                                           |
                                           v
[DRV8833 Dual H-Bridge Driver] <--(Hardware Timer PWM @ 20 kHz)--+
STEP 4

Required Hardware Bill of Materials (BOM)

Hardware Component Qty Engineering Specification
STM32F401 "Black Pill" ARM Cortex-M4 MCU 1 84 MHz, 3.3V logic, Hardware FPU
MPU-6050 6-DOF IMU (Accel + Gyro) 1 I2C Interface, 3.3V logic
DRV8833 Dual H-Bridge Motor Driver 1 Up to 10.8V motor rail, 1.2A RMS/channel
12V Metal Gearmotors with Quadrature Encoders 2 300 RPM, 30:1 gear ratio
LM2596 Step-Down Buck Converter Module 1 12V down to 5.0V / 3.3V logic supply
11.1V 3S LiPo Battery (1500mAh, 25C) 1 Main traction power pack
100µF 25V Electrolytic Low-ESR Capacitor 2 Motor supply rail decoupling
STEP 5

Wiring, Pinout & Schematics Mapping

• STM32 PB6 (SCL) -> MPU-6050 SCL (with 3.3kΩ pull-up to 3.3V) • STM32 PB7 (SDA) -> MPU-6050 SDA (with 3.3kΩ pull-up to 3.3V) • STM32 PA8 (TIM1_CH1 PWM) -> DRV8833 IN1 • STM32 PA9 (TIM1_CH2 PWM) -> DRV8833 IN2 • STM32 PA10 (TIM1_CH3 PWM) -> DRV8833 IN3 • STM32 PA11 (TIM1_CH4 PWM) -> DRV8833 IN4 • DRV8833 VM -> +11.1V Battery rail (with 100µF buffer cap across VM and GND) • Common Ground: Connect Battery (-), STM32 GND, and DRV8833 GND together.
STEP 6

Firmware Implementation & Algorithms

// Discrete PID Loop with Anti-Windup Clamping (ANSI C)
#include <math.h>

typedef struct {
    float kp, ki, kd;
    float integrator;
    float prev_error;
    float max_output;
    float min_output;
    float dt;
} PIDController;

float pid_compute(PIDController *pid, float setpoint, float measured_val) {
    float error = setpoint - measured_val;
    
    // Proportional term
    float p_term = pid->kp * error;
    
    // Integral term with forward Euler integration
    float new_integrator = pid->integrator + (pid->ki * error * pid->dt);
    
    // Derivative term (on error or process variable)
    float d_term = pid->kd * (error - pid->prev_error) / pid->dt;
    pid->prev_error = error;
    
    // Raw output before saturation
    float raw_output = p_term + new_integrator + d_term;
    float clamped_output = raw_output;
    
    // Clamp actuator output boundaries
    if (clamped_output > pid->max_output) {
        clamped_output = pid->max_output;
    } else if (clamped_output < pid->min_output) {
        clamped_output = pid->min_output;
    }
    
    // Anti-Windup: Only accumulate integrator if not in severe saturation
    if (raw_output == clamped_output || (error * raw_output) < 0.0f) {
        pid->integrator = new_integrator;
    }
    
    return clamped_output;
}
STEP 7

Bench Testing & Waveform Verification

1. Connect an oscilloscope probe to STM32 PA8 (PWM output) and verify 20 kHz carrier frequency. 2. Log loop cycle time over UART: Ensure total execution time remains under 1.2 ms, comfortably inside the 10.0 ms (100 Hz) time budget. 3. Suspend robot by pivot; impart a small 5° displacement. Verify the motors instantly apply corrective torque towards the center.
STEP 8

Troubleshooting & Common Failure Modes

• Problem: Violent high-frequency chattering. Solution: Reduce $K_d gain or apply a digital low-pass filter (cut-off at 25 Hz) to the gyro rate signal. • Problem: Robot slowly drifts until motors saturate. Solution: Calibrate accelerometer zero-g bias offsets while the chassis is strictly level. • Problem: I2C bus hangs indefinitely when motors switch rapidly. Solution: Add optocoupler isolation or twisted-pair shielded cables between IMU and microcontroller.
STEP 9

Extensions & Undergraduate Research Challenges

1. Replace the single-variable PID with a Linear Quadratic Regulator (LQR) utilizing state vector $\mathbf{x} = [\theta, \dot{\theta}, x, \dot{x}]^T$. 2. Implement an Extended Kalman Filter (EKF) to fuse encoder wheel odometry with IMU acceleration for precise planar navigation.
All Engineering Guides
Closed-Loop Discrete PID Control & Inverted Pendulum Balancing
Control Systems & Robotics • 25 min
CAN-Bus 2.0B Telemetry Node with Industrial Sensor Fusion
Embedded Systems & Automotive • 20 min
Precision Dual-Axis Stepper Motion Controller with S-Curve Acceleration
Mechatronics & Motion Control • 22 min
IoT Environmental Monitoring Station with OLED & Secure Telemetry
Internet of Things (IoT) • 18 min
Closed-Loop DC Motor Velocity Control with Optical Quadrature Encoder
Power Electronics & Motion • 20 min
Astable 555 Timer & 74HC595 Shift Register Digital Sequencer
Discrete Electronics & Digital Logic • 16 min
Field-Oriented Control (FOC) & Space Vector Modulation for BLDC Motors
Power Electronics & Motors • 28 min
High-Efficiency Synchronous Buck DC-DC Converter Design
Power Electronics & Energy • 24 min
Discrete Kalman Filter IMU Sensor Fusion for Tilt & Orientation
Control Systems & Robotics • 26 min
Industrial Modbus RTU Slave Node over Galvanically Isolated RS-485
Industrial Automation • 22 min
4th-Order Sallen-Key Active Butterworth Filter for Sensor Anti-Aliasing
Electronics Fundamentals • 22 min
Mobile Robot Differential Odometry with 4X Hardware Quadrature Decoding
Robotics & Automation • 24 min
Discrete N-Channel MOSFET H-Bridge with Bootstrap Gate Drive
Electronics & Motor Control • 25 min
High-Speed SPI NOR Flash Black-Box Flight Data Logger
Embedded Systems & IoT • 22 min
MPU-6050 Digital Motion Processor (DMP) Quaternion Spatial Tracking
Sensors & Embedded Algorithms • 24 min
Deterministic Multitasking Architecture with FreeRTOS Kernel
Embedded Systems & Software • 25 min
Ask LUNA About This Lab

Ask LUNA for circuit calculations, state-space equations, tuning parameters, or component substitutes.

Hardware Catalog

Inspect verified electrical specs, voltage rails, and pinouts across all 10 component categories.

Browse Components →