Project 6: Reaction Wheel PID Controller (The Mover)
Implement a reaction-wheel attitude controller with PID loops, saturation handling, and momentum management, validated against a rigid-body simulation.
Quick Reference
| Attribute | Value |
|---|---|
| Difficulty | Level 3: Advanced |
| Time Estimate | 1-2 weeks |
| Main Programming Language | Python |
| Alternative Programming Languages | C, C++ |
| Coolness Level | Level 4: Control Systems Pro |
| Business Potential | Level 3: ADCS Tooling |
| Prerequisites | Control theory basics, dynamics, PID tuning |
| Key Topics | Rigid body dynamics, PID control, actuator saturation |
1. Learning Objectives
By completing this project, you will:
- Model spacecraft rotational dynamics and reaction wheel actuation.
- Design PID controllers for attitude error correction.
- Implement saturation and anti-windup strategies.
- Simulate control performance under disturbances.
- Understand momentum management constraints.
2. All Theory Needed (Per-Concept Breakdown)
Rigid Body Dynamics and Reaction Wheel Actuation
Fundamentals A spacecraft’s attitude changes according to rotational dynamics: torque equals inertia times angular acceleration. Reaction wheels generate torque by spinning up or down. The spacecraft and wheels exchange angular momentum; torque on the wheel produces equal and opposite torque on the spacecraft. Understanding this relationship is critical: if you command a wheel beyond its limits, you cannot produce more torque. Modeling inertia correctly is the foundation of controller design.
Deep Dive into the concept Rigid body dynamics are described by Euler’s equation: I * omega_dot + omega x (I * omega) = tau, where I is the inertia tensor, omega is angular velocity, and tau is applied torque. For small satellite attitude control, you can approximate I as diagonal (Ixx, Iyy, Izz) and neglect cross-coupling for initial design. Reaction wheels produce torque by changing their spin rate: tau = -I_w * omega_w_dot, where I_w is wheel inertia and omega_w_dot is wheel acceleration. The negative sign indicates equal and opposite torque on the spacecraft.
A reaction wheel system usually has three wheels aligned with body axes. The controller computes desired torques in body coordinates. These torques are then mapped to wheel accelerations. However, wheels have maximum torque and speed limits. When the wheel saturates, you cannot apply additional torque. This is a key design constraint; a controller that ignores saturation will become unstable because it assumes more torque than available.
Another phenomenon is momentum buildup. External disturbances (magnetic torque, atmospheric drag, solar pressure) cause the wheels to accumulate angular momentum. Over time, wheels saturate even if the controller is stable. In real missions, you offload momentum using magnetorquers or thrusters. In this project, you will at least model wheel speed limits and observe saturation behavior. A simple momentum management strategy is to apply a bias torque to keep wheel speeds centered, or to schedule momentum dumps when speeds approach limits.
Simulation is essential: implement a rigid body simulator where you apply control torques and integrate angular velocity and attitude. Use small time steps for stability. Validate the model with known behaviors (e.g., constant torque yields linear omega growth). If the model is wrong, your PID tuning will be meaningless.
How this fit on projects This concept drives Section 3.2 control requirements and Section 4.4 dynamics modeling, and relies on P05 attitude estimation.
Definitions & key terms
- Inertia tensor (I) -> Matrix describing resistance to angular acceleration.
- Reaction wheel -> Actuator that applies torque by changing wheel speed.
- Saturation -> Actuator limit (max torque or speed).
Mental model diagram (ASCII)
Desired Torque -> Wheel Accel -> Reaction Torque -> Spacecraft omega_dot
How it works (step-by-step, with invariants and failure modes)
- Compute desired torque from controller.
- Clamp torque to wheel limits.
- Update wheel speeds and spacecraft angular velocity.
- Integrate attitude.
Invariants: wheel speeds within limits; torque command limited; inertia constant.
Failure modes: unmodeled cross-coupling, saturation ignored, unstable integration.
Minimal concrete example
tau = np.clip(tau_cmd, -tau_max, tau_max)
omega_dot = np.linalg.inv(I) @ (tau - np.cross(omega, I @ omega))
Common misconceptions
- “Wheels can produce any torque” -> Torque is limited by motor and power.
- “Saturation only affects extreme cases” -> It can dominate long-term behavior.
Check-your-understanding questions
- Why does wheel saturation break PID assumptions?
- What is momentum buildup and why does it happen?
- How does inertia affect required torque?
Check-your-understanding answers
- PID assumes commanded torque equals applied torque; saturation violates that.
- External disturbances push wheel speeds toward limits.
- Higher inertia requires more torque to achieve the same angular acceleration.
Real-world applications
- Attitude control for CubeSats and small spacecraft.
- Reaction wheel control in Earth observation missions.
Where you’ll apply it
- See Section 3.2 (requirements) and Section 5.10 Phase 2.
- Also used in: P05-the-attitude-estimator-sensor-fusion.md
References
- Wertz, Spacecraft Attitude Determination and Control
- Hughes, Spacecraft Attitude Dynamics
Key insights Control authority is limited; your software must respect actuator constraints.
Summary Modeling rigid body dynamics and wheel limits is foundational for control.
Homework/Exercises to practice the concept
- Compute torque required to rotate 5 degrees in 10 seconds given Ixx.
Solutions to the homework/exercises
- Use theta = 0.5 * alpha * t^2; solve for alpha then tau = I * alpha.
PID Control, Tuning, and Anti-Windup
Fundamentals PID controllers combine proportional, integral, and derivative terms to reduce error. P responds to current error, I accumulates past error, and D predicts future error. PID is popular because it is simple and effective. But in spacecraft control, actuator saturation and noise can destabilize PID. Anti-windup strategies prevent the integral term from growing when the actuator is saturated. Correct tuning is essential for stability.
Deep Dive into the concept PID control aims to drive attitude error to zero. The proportional term generates torque proportional to error. The derivative term damps motion by reacting to angular velocity. The integral term eliminates steady-state bias, such as a constant disturbance torque. In attitude control, you often use PD control (P + D) and add a small integral term if needed. This is because integral action can accumulate and cause overshoot if not carefully limited.
Tuning PID gains is both art and science. One approach is to start with a PD controller: choose Kp to achieve the desired stiffness and Kd to damp oscillations. Increase Kp until you see oscillations, then add Kd to damp them. Add Ki only if steady-state error persists. Use the spacecraft inertia to estimate gain ranges: higher inertia requires higher gains to achieve the same response. Always test in simulation with realistic disturbances.
Anti-windup is critical. When actuators saturate, the controller cannot apply the commanded torque. If the integral term continues to accumulate error, it will overshoot and cause long recovery times. Anti-windup strategies include clamping the integrator, back-calculation, or freezing the integrator when saturation occurs. For this project, a simple clamp or freeze is sufficient. The key is to ensure that the integrator does not dominate when you are torque-limited.
Noise sensitivity is another issue. The derivative term amplifies noise. In attitude control, you often compute the D term from measured angular velocity rather than differentiating the error. This provides a more stable derivative estimate. You can also low-pass filter the derivative term to reduce noise.
Stability analysis can be approximate. You can measure step response: command a small attitude change and observe overshoot and settling time. A stable controller should settle within mission constraints (e.g., 10-30 seconds). You can also use frequency response tools, but in this project, simulation-based tuning is sufficient.
How this fit on projects This concept drives Section 3.2 control requirements and Section 6 testing (step response).
Definitions & key terms
- Kp, Ki, Kd -> Proportional, integral, derivative gains.
- Anti-windup -> Strategy to prevent integrator saturation.
- Settling time -> Time for error to enter and stay within bounds.
Mental model diagram (ASCII)
Error -> [P + I + D] -> Torque Command -> Actuator
How it works (step-by-step, with invariants and failure modes)
- Compute attitude error and angular velocity.
- Compute PID torque command.
- Apply saturation and anti-windup.
- Update dynamics and repeat.
Invariants: controller updates at fixed dt; integral term bounded.
Failure modes: overshoot, oscillations, integral windup.
Minimal concrete example
integral = clamp(integral + err * dt, -i_max, i_max)
tau = Kp*err + Kd*omega + Ki*integral
Common misconceptions
- “More integral gain improves accuracy” -> It often destabilizes.
- “Derivative term is optional” -> It provides essential damping.
Check-your-understanding questions
- Why does actuator saturation cause integral windup?
- How does derivative action help stability?
- Why might you omit the integral term initially?
Check-your-understanding answers
- The integrator keeps accumulating error despite limited actuation.
- It damps velocity and reduces overshoot.
- To avoid windup and simplify tuning.
Real-world applications
- Reaction wheel controllers in small satellites.
- Attitude control loops in drones and robots.
Where you’ll apply it
- See Section 3.2 (requirements) and Section 6.2 (step response tests).
- Also used in: P05-the-attitude-estimator-sensor-fusion.md
References
- Franklin, Powell, Emami-Naeini, Feedback Control of Dynamic Systems
- Astrom & Murray, Feedback Systems
Key insights PID is simple but unforgiving; tuning and anti-windup are non-negotiable.
Summary A stable PID controller requires proper gains, saturation handling, and damping.
Homework/Exercises to practice the concept
- Tune Kp and Kd to achieve a 10s settling time in simulation.
Solutions to the homework/exercises
- Increase Kp until oscillation, then add Kd to damp; tune iteratively.
3. Project Specification
3.1 What You Will Build
A reaction wheel controller with PID loops, saturation and anti-windup handling, and a rigid-body simulator to validate attitude stabilization.
3.2 Functional Requirements
- Rigid-body simulator for attitude and angular velocity.
- PID control loop to command torques.
- Saturation handling and anti-windup.
- Performance evaluation via step response metrics.
3.3 Non-Functional Requirements
- Determinism: fixed dt and deterministic disturbances.
- Stability: no divergence or runaway oscillation.
- Transparency: logs of torque commands and wheel speeds.
3.4 Example Usage / Output
$ python rw_pid.py --step 5deg --dt 0.1
[INFO] Settling time: 12.3 s
[PLOT] attitude_response.png
3.5 Data Formats / Schemas / Protocols
Config JSON:
{"I":[0.02,0.02,0.04],"Kp":0.8,"Kd":0.12,"Ki":0.01,"tau_max":0.02}
3.6 Edge Cases
- Torque saturation during large steps.
- Integrator windup if anti-windup missing.
- Disturbance torques causing steady-state error.
3.7 Real World Outcome
A plot showing stable convergence of attitude error with bounded wheel speeds.
3.7.1 How to Run (Copy/Paste)
python rw_pid.py --config configs/nominal.json --step 5
3.7.2 Golden Path Demo (Deterministic)
- Use fixed config and dt.
- Compare output with
golden_response.csv.
3.7.3 Failure Demo (Deterministic)
python rw_pid.py --config configs/no_antiwindup.json --step 15
Expected: overshoot and long settling; exit code 3.
3.7.4 If CLI: Exact Terminal Transcript
$ python rw_pid.py --config configs/nominal.json --step 5
[INFO] Settling time: 12.3 s
ExitCode=0
4. Solution Architecture
4.1 High-Level Design
Attitude Error -> PID -> Torque Cmd -> Saturation -> Dynamics -> New Attitude
4.2 Key Components
| Component | Responsibility | Key Decisions |
|---|---|---|
| Dynamics Model | Simulate rigid body | Integrator choice |
| PID Controller | Compute torque | Gain tuning |
| Saturation | Enforce limits | Clamp strategy |
| Evaluator | Compute settling time | Threshold definition |
4.3 Data Structures (No Full Code)
class ControllerState:
integral = np.zeros(3)
4.4 Algorithm Overview
Key Algorithm: PID loop
- Compute attitude error vector.
- Compute torque = Kperr + Kdomega + Ki*integral.
- Clamp torque and apply anti-windup.
- Update rigid body dynamics.
Complexity Analysis:
- Time: O(1) per step.
- Space: O(1).
5. Implementation Guide
5.1 Development Environment Setup
python -m venv .venv
source .venv/bin/activate
pip install numpy matplotlib
5.2 Project Structure
project-root/
+-- rw_pid.py
+-- configs/
+-- logs/
+-- README.md
5.3 The Core Question You’re Answering
“How do you point a spacecraft using only spinning wheels?”
5.4 Concepts You Must Understand First
- Rigid body dynamics.
- PID control and tuning.
- Actuator saturation.
5.5 Questions to Guide Your Design
- What settling time is acceptable for your mission?
- How will you detect saturation and clamp integral?
- What disturbance torques should you simulate?
5.6 Thinking Exercise
Compute the torque required to rotate 10 degrees in 20 seconds for given inertia.
5.7 The Interview Questions They’ll Ask
- “Why do reaction wheels saturate?”
- “How does PID tuning affect overshoot?”
- “What is anti-windup and why is it important?”
5.8 Hints in Layers
Hint 1: Start with a PD controller and zero integral term.
Hint 2: Add saturation clamping and observe response.
Hint 3: Add integral term with clamping.
Hint 4: Add disturbance torques to test robustness.
5.9 Books That Will Help
| Topic | Book | Chapter |
|---|---|---|
| Attitude control | Wertz | Control chapters |
| PID tuning | Astrom & Murray | PID sections |
| Dynamics | Hughes | Rigid body dynamics |
5.10 Implementation Phases
Phase 1: Dynamics Simulator (3-4 days)
Goals: simulate attitude motion. Tasks: integrate Euler equations. Checkpoint: constant torque yields expected angular acceleration.
Phase 2: PID Controller (3-4 days)
Goals: stable attitude control. Tasks: implement P and D terms, tune gains. Checkpoint: settle within target time.
Phase 3: Saturation + Anti-windup (2-3 days)
Goals: handle limits without instability. Tasks: clamp torque, limit integral. Checkpoint: no runaway when torque saturates.
5.11 Key Implementation Decisions
| Decision | Options | Recommendation | Rationale |
|---|---|---|---|
| Integration | Euler / RK4 | RK4 | Improved stability |
| Control law | PD / PID | PD+small I | Simpler tuning |
| Saturation handling | clamp / back-calc | clamp | Easy and effective |
6. Testing Strategy
6.1 Test Categories
| Category | Purpose | Examples |
|---|---|---|
| Unit Tests | PID math | known inputs |
| Integration Tests | Step response | 5 deg step |
| Edge Case Tests | Saturation | 20 deg step |
6.2 Critical Test Cases
- Small step: stable response, low overshoot.
- Large step: saturation handled with anti-windup.
- Disturbance: controller rejects constant torque.
6.3 Test Data
configs/nominal.json
configs/high_disturbance.json
7. Common Pitfalls & Debugging
7.1 Frequent Mistakes
| Pitfall | Symptom | Solution |
|---|---|---|
| No normalization | Attitude drift | Normalize quaternion |
| Integral windup | Huge overshoot | Clamp integral |
| Poor tuning | Oscillation | Lower Kp, raise Kd |
7.2 Debugging Strategies
- Plot torque commands and wheel speeds.
- Check stability with smaller dt.
7.3 Performance Traps
None; focus on stability and correct physics.
8. Extensions & Challenges
8.1 Beginner Extensions
- Add 2-axis control only (reduced complexity).
8.2 Intermediate Extensions
- Add momentum dump event simulation.
8.3 Advanced Extensions
- Design LQR controller and compare to PID.
9. Real-World Connections
9.1 Industry Applications
- Reaction wheel control in Earth observation satellites.
- Attitude stabilization in scientific missions.
9.2 Related Open Source Projects
- cFS attitude control examples.
- Orekit attitude dynamics modules.
9.3 Interview Relevance
- Demonstrates control theory applied to real systems.
10. Resources
10.1 Essential Reading
- Wertz, Spacecraft Attitude Determination and Control.
- Astrom & Murray, Feedback Systems.
10.2 Video Resources
- Control systems lectures (MIT OpenCourseWare).
10.3 Tools & Documentation
- numpy, matplotlib for simulation.
10.4 Related Projects in This Series
11. Self-Assessment Checklist
11.1 Understanding
- I can derive Euler’s equation for rigid body rotation.
- I can explain PID tuning tradeoffs.
- I can describe momentum saturation effects.
11.2 Implementation
- Controller stabilizes attitude within required time.
- Saturation and anti-windup behave correctly.
- Deterministic outputs with fixed dt.
11.3 Growth
- I can propose a momentum dumping strategy.
12. Submission / Completion Criteria
Minimum Viable Completion:
- PD controller stabilizes attitude for small steps.
Full Completion:
- PID with anti-windup and saturation handling.
Excellence (Going Above & Beyond):
- Compare PID to LQR or add momentum dump modeling.