Skip to content

chaffybird56/Upright-Pendulum

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

14 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐ŸŽฏ Inverted Pendulum Control System

Imagine balancing a stick on your finger. Now imagine doing it automatically with a robot. This project does exactly thatโ€”using advanced control theory, custom electronics, and real-time software to keep an inverted pendulum perfectly balanced.


๐ŸŽฌ See It In Action

IMG_2700.mp4

๐Ÿง  What's the Big Idea? (Simple Explanation)

Think of balancing a broomstick on your palm. You can see where the stick is (the angle), but you can't directly feel how fast it's moving. Yet your brain somehow figures it out and moves your hand to keep it balanced.

This project replicates that process:

  1. Sensors measure the pendulum's angle (like your eyes seeing the stick)
  2. A "smart guesser" (called an observer) figures out how fast it's moving (like your brain estimating speed)
  3. A controller calculates the right motor command to keep it balanced (like your hand moving)
  4. Custom circuits translate these commands into actual motor movements

The magic happens 1000 times per secondโ€”fast enough that the pendulum never falls!


๐ŸŽฏ What This Project Includes

This is a complete mechatronics system combining:

  • โœ… Control Theory: State-feedback control with full-state observer
  • โœ… Control System Design: PID tuning (Ziegler-Nichols, Cohen-Coon), root locus analysis, Bode plots, stability margins
  • โœ… Hardware Design: Custom analogue and digital circuits for sensors and actuators
  • โœ… Power Management: Efficient power supplies and protection circuits
  • โœ… Signal Processing: Filtering and conditioning for clean sensor data
  • โœ… PCB Design: Complete printed circuit board design workflow
  • โœ… Testing Infrastructure: Comprehensive functional and environmental tests

๐Ÿ–ผ๏ธ How It Works (Visual)

Inverted pendulum schematic
Mechanism Overview. A rotary base (joint 1) moves the pendulum link (joint 2). Sensors measure angles; the controller estimates velocities and commands the motor.

๐Ÿ”ง System Architecture

The Control Problem

The pendulum has two joints:

  • Joint 1 (base): Can rotate horizontally
  • Joint 2 (pendulum): The link that needs to stay upright

We can measure the angles ($q_1$, $q_2$), but we can't directly measure how fast they're changing ($\dot{q}_1$, $\dot{q}_2$). However, the controller needs all four values to work properly.

The Solution: Observer-Based Control

Instead of measuring everything, we:

  1. Predict what the velocities should be (using a mathematical model)
  2. Compare our predictions to the actual measured angles
  3. Correct our predictions based on the difference
  4. Control the motor using these corrected estimates

This happens continuously in a feedback loop running at 1 kHz (1000 times per second).


๐Ÿ› ๏ธ Hardware Implementation

Sensor Interface Circuits

Encoders measure joint angles with high precision:

  • Type: Incremental optical encoders (2048 pulses/revolution)
  • Interface: Quadrature decoding via LS7366R ICs
  • Signal Conditioning: Noise filtering and level shifting
  • Communication: SPI interface to microcontroller

๐Ÿ“„ Details: See hardware/circuits/sensor_interface.md

Actuator Drive Circuits

DC Motor drives the base to balance the pendulum:

  • Power: 24V DC, 2A continuous (5A peak)
  • Driver: DRV8871 H-bridge with integrated current sensing
  • Control: 20 kHz PWM for smooth operation
  • Protection: Overcurrent and thermal shutdown

๐Ÿ“„ Details: See hardware/circuits/actuator_drive.md

Power Management

Efficient power distribution for all subsystems:

  • 24V Input: Main power supply (wall adapter or battery)
  • 3.3V Regulator: For microcontroller and digital logic (85% efficiency)
  • 5V Regulator: For encoder power (88% efficiency)
  • Protection: Overvoltage, undervoltage, and overcurrent protection

๐Ÿ“„ Details: See hardware/circuits/power_management.md

Signal Processing

Clean, accurate sensor data through:

  • Anti-aliasing Filters: Remove high-frequency noise before ADC
  • Current Sensing: Precise motor current measurement (1.2 mA resolution)
  • Voltage Monitoring: System voltage tracking for diagnostics
  • Digital Filtering: Software filters for angle rate estimation

๐Ÿ“„ Details: See hardware/circuits/signal_processing.md

PCB Design

Complete printed circuit board design:

  • 4-Layer Stackup: Signal, ground, power planes
  • Component Selection: Detailed analysis and alternatives
  • Layout Guidelines: Thermal management, EMI reduction
  • Manufacturing: Gerber files, BOM, assembly notes

๐Ÿ“„ Details:


๐Ÿงช Testing Infrastructure

Functional Tests

Comprehensive validation of all system components:

  • โœ… Sensor accuracy and noise levels
  • โœ… Actuator response time and characteristics
  • โœ… Control loop stability
  • โœ… Observer performance
  • โœ… Signal processing accuracy
  • โœ… Power management

๐Ÿ“„ Details: See tests/functional_tests.m

Environmental Tests

Reliability testing under various conditions:

  • ๐ŸŒก๏ธ Temperature: Operation from -10ยฐC to 60ยฐC
  • ๐Ÿ“ณ Vibration: Resistance to 10-1000 Hz mechanical vibration
  • โฑ๏ธ Extended Operation: 1-hour continuous operation test
  • โšก Power Variation: Behavior with 20-28V input voltage
  • ๐Ÿ”„ Thermal Cycling: Rapid temperature change stress test

๐Ÿ“„ Details: See tests/environmental_tests.m

Run Tests:

% Functional tests
run('tests/functional_tests.m')

% Environmental tests
run('tests/environmental_tests.m')

๐Ÿ“Š Results

Simulink Model

Simulink output-feedback model
Control System Implementation. Observer estimates unmeasured states; controller applies state-feedback using estimates.

Hardware Performance

After tuning the observer speed:

  • 20ร— scaling: System stabilized but showed oscillation
  • 15ร— scaling: Smooth behavior with minimal control effort
Angles and input with 15x observer
Hardware Results. Joint angles (top) and motor voltage (bottom) with observer poles at 15ร— the controller poles.

๐Ÿงฎ The Mathematics (Technical Deep Dive)

System Model

The pendulum dynamics are linearized about the upright position:

$$ \dot{x} = A x + B u, \qquad y = C x $$

where the state vector is:

$$ x = \begin{bmatrix} q_1 & q_2 & \dot{q}_1 & \dot{q}_2 \end{bmatrix}^\top $$

and only angles are measured:

$$ y = \begin{bmatrix} q_1 & q_2 \end{bmatrix}^\top $$

State-Feedback Control

If all states were available, the control law would be:

$$ u = -K x \quad \Rightarrow \quad \dot{x} = (A - B K) x $$

The gain matrix $K$ is designed via pole placement to achieve desired closed-loop eigenvalues:

$$ \lambda_{desired} = {-10 \pm 10j,\ -15,\ -18} $$

These poles provide:

  • Fast response (real parts around -10 to -18)
  • Good damping (complex poles with damping ratio ~0.707)
  • Stability (all poles in left half-plane)

Full-State Observer

Since velocities are not measured, we use an observer:

$$ \dot{\hat{x}} = A \hat{x} + B u + L(y - C \hat{x}) $$

The correction term $L(y - C\hat{x})$ drives the estimate toward the true state. The observer gain $L$ is designed so that $(A - LC)$ has eigenvalues 15ร— faster than the controller poles, ensuring rapid convergence.

Estimation Error Dynamics

The estimation error $\tilde{x} = x - \hat{x}$ evolves as:

$$ \dot{\tilde{x}} = (A - L C) \tilde{x} $$

By making $(A - LC)$ stable with fast eigenvalues, the error decays quickly, so $\hat{x} \approx x$ during operation.

Output-Feedback Control

The actual control law uses the state estimate:

$$ u = -K \hat{x} $$

The separation principle guarantees that if both $(A - BK)$ and $(A - LC)$ are stable, the combined system is stable.


๐Ÿ’ป Implementation Details

Software

  1. System Identification: Linearize pendulum model and identify parameters
  2. Controller Design: Compute $K$ via pole placement
  3. Observer Design: Compute $L$ with poles 15ร— faster than controller
  4. Control System Analysis: PID tuning, root locus, Bode plots, stability margins
  5. Simulink Model: Implement observer and controller blocks
  6. Real-Time Execution: Run at 1 kHz on STM32F4 microcontroller

Hardware

  1. Sensors: Optical encoders with quadrature decoding
  2. Actuator: 24V DC motor with H-bridge driver
  3. Processing: STM32F407VGT6 microcontroller (ARM Cortex-M4)
  4. Power: Multi-rail power supply with protection circuits
  5. PCB: Custom 4-layer board with optimized layout

๐Ÿ“ Project Structure

Upright-Pendulum-main/
โ”œโ”€โ”€ README.md                    # This file
โ”œโ”€โ”€ LICENSE                      # MIT License
โ”‚
โ”œโ”€โ”€ scripts/
โ”‚   โ”œโ”€โ”€ script_phase.m               # Controller and observer design
โ”‚   โ”œโ”€โ”€ actual_graph.m               # Hardware data visualization
โ”‚   โ”œโ”€โ”€ control_design_tools.m       # Control system design and analysis
โ”‚   โ””โ”€โ”€ pid_tuning_demo.m            # PID tuning method comparison
โ”‚
โ”œโ”€โ”€ models/
โ”‚   โ”œโ”€โ”€ model1.slx                  # Simulink control model
โ”‚   โ””โ”€โ”€ model1.1.slx                # Updated Simulink model
โ”‚
โ”œโ”€โ”€ data/
โ”‚   โ”œโ”€โ”€ qm_actual-15.mat            # Hardware test data (angles, 15ร— observer)
โ”‚   โ”œโ”€โ”€ qm_actual-20.mat            # Hardware test data (angles, 20ร— observer)
โ”‚   โ”œโ”€โ”€ um_actual-15.mat            # Hardware test data (input, 15ร— observer)
โ”‚   โ””โ”€โ”€ um_actual-20.mat            # Hardware test data (input, 20ร— observer)
โ”‚
โ”œโ”€โ”€ hardware/
โ”‚   โ”œโ”€โ”€ circuits/
โ”‚   โ”‚   โ”œโ”€โ”€ sensor_interface.md      # Encoder circuit design
โ”‚   โ”‚   โ”œโ”€โ”€ actuator_drive.md        # Motor driver circuits
โ”‚   โ”‚   โ”œโ”€โ”€ power_management.md      # Power supply design
โ”‚   โ”‚   โ””โ”€โ”€ signal_processing.md     # Signal conditioning
โ”‚   โ””โ”€โ”€ pcb/
โ”‚       โ”œโ”€โ”€ design_workflow.md       # PCB design process
โ”‚       โ””โ”€โ”€ component_selection.md   # Component analysis
โ”‚
โ”œโ”€โ”€ tests/
โ”‚   โ”œโ”€โ”€ README.md                    # Test documentation
โ”‚   โ”œโ”€โ”€ functional_tests.m           # Functional validation
โ”‚   โ””โ”€โ”€ environmental_tests.m        # Environmental testing
โ”‚
โ””โ”€โ”€ docs/
    โ””โ”€โ”€ PROJECT_STRUCTURE.md          # Project organization documentation

๐Ÿš€ Getting Started

Prerequisites

  • MATLAB (R2018b or later) with:
    • Control System Toolbox
    • Simulink
    • Signal Processing Toolbox (for tests)
  • Hardware (optional, for physical implementation):
    • Inverted pendulum rig
    • STM32F4 development board or custom PCB
    • Encoders, motor, power supply

Control System Design Tools

The project includes control system design and analysis tools for controller development and performance evaluation.

PID Tuning Methods:

  • Ziegler-Nichols ultimate gain method for PID parameter selection
  • Cohen-Coon tuning for first-order plus dead time systems
  • Automatic parameter calculation from system step response

Frequency Domain Analysis:

  • Root locus plots for gain selection and stability analysis
  • Bode plots showing magnitude and phase response
  • Gain and phase margin calculation for stability assessment

Time Domain Analysis:

  • Step response with performance metrics including rise time, settling time, and overshoot
  • Open-loop versus closed-loop comparison
  • Steady-state error analysis

Usage:

% Run comprehensive control design analysis
run('scripts/control_design_tools.m')

% Compare PID tuning methods
run('scripts/pid_tuning_demo.m')

The scripts generate plots showing root locus, Bode plots, step responses, and stability margins, providing a complete view of the control system's performance characteristics.

Running the Code

  1. Design Controller and Observer:

    run('scripts/script_phase.m')
  2. Simulate in Simulink:

    • Open models/model1.slx or models/model1.1.slx
    • Run simulation
    • Analyze results
  3. Visualize Hardware Data:

    run('scripts/actual_graph.m')
  4. Run Tests:

    run('tests/functional_tests.m')
    run('tests/environmental_tests.m')

๐Ÿ“Œ Key Design Decisions

Observer Speed vs. Noise

  • Faster observers track better but amplify sensor noise
  • Slower observers are more robust but lag behind
  • Sweet spot: Observer poles ~15ร— faster than controller poles

Actuator Limits

  • Motor voltage limited to ยฑ24V
  • Unmodeled friction affects performance
  • Current limiting protects hardware

Signal Processing

  • 1 kHz sampling rate: Matches control loop frequency
  • Anti-aliasing filters: Prevent high-frequency noise aliasing
  • Digital filters: Smooth angle rate estimates

๐ŸŽ“ Learning Resources

Control Theory Concepts

  • State-Space Representation: Modern control theory foundation
  • Pole Placement: Direct eigenvalue assignment method
  • Observers: State estimation from partial measurements
  • Separation Principle: Independent controller/observer design

Hardware Design Concepts

  • Sensor Interfaces: Encoder decoding, signal conditioning
  • Motor Control: PWM, H-bridge drivers, current sensing
  • Power Management: Voltage regulation, protection circuits
  • PCB Design: Layout, thermal management, EMI reduction

๐Ÿง  Glossary

State Feedback โ€” Control law $u = -Kx$ using full state vector
Full-State Observer โ€” Estimator $\dot{\hat{x}} = A\hat{x} + Bu + L(y - C\hat{x})$ that reconstructs unmeasured states
Pole Placement โ€” Design method choosing eigenvalues of $(A-BK)$ or $(A-LC)$ to shape system dynamics
Separation Principle โ€” Allows independent design of controller ($K$) and observer ($L$); stability of both implies closed-loop stability
Quadrature Decoder โ€” Circuit that converts encoder A/B signals into position counts
H-Bridge โ€” Motor driver circuit allowing bidirectional current flow
PWM โ€” Pulse-width modulation for efficient motor control


๐Ÿ“„ License

MIT License โ€” see LICENSE file for details.


๐Ÿ™ Acknowledgments

This project demonstrates the integration of:

  • Control systems theory
  • Embedded systems design
  • Analog and digital circuit design
  • PCB layout and manufacturing
  • System testing and validation

A complete mechatronics system from theory to hardware! ๐ŸŽฏ

About

Stabilizes inverted pendulum using state-feedback and observer

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages