Skip to content

Latest commit

 

History

History
282 lines (218 loc) · 13.3 KB

codebase.md

File metadata and controls

282 lines (218 loc) · 13.3 KB

● PID_TVC_GUI Codebase Explanation

Overview

This project implements a Proportional-Integral-Derivative (PID) controller for Thrust Vector Control (TVC) with a Graphical User Interface (GUI). Think of it as the "brain" and "control panel" for a rocket's steering system:

  • PID Controller: Continuously adjusts the rocket's nozzle direction to maintain the desired flight path (like cruise control for direction)
  • Thrust Vector Control: Physically tilts the rocket engine to steer the vehicle
  • GUI: Provides a visual interface to monitor and adjust parameters in real-time

The system is designed for model rocketry but follows principles used in aerospace engineering. It's organized using modern C++ practices with clear separation of concerns, making it portable across different hardware platforms.


Chronological Codebase Walkthrough

We'll explain the codebase in the order you'd typically encounter it when building/using the system: from core logic → hardware abstraction → platform implementation → testing/validation → tools → documentation.

  1. Core Logic (core/)

This is the "brain" containing all the flight control algorithms - completely independent of specific hardware.

Purpose: Contains the mathematical and logical heart of the TVC system. All code here is pure C++17 with no hardware dependencies, making it testable and portable.

Key Subdirectories & Files:

  • estimator/ - The "sensor fusion" system
    • Purpose: Combines data from multiple sensors (like gyroscopes and accelerometers) to estimate the rocket's actual orientation (pitch, yaw, roll)
    • Key File: estimator.hpp - Defines the abstract interface for different estimation algorithms (complementary filter, Kalman filter, etc.)
    • Analogy: Like your inner ear combining motion and gravity sensors to tell you which way is up
  • pid/ - The primary controller
    • Purpose: Implements the Proportional-Integral-Derivative control law that calculates how much to adjust the nozzle based on orientation errors
    • Key File: pid_controller.hpp - Implements a PID controller with anti-windup (prevents integral term from accumulating too much) and derivative filtering (reduces noise sensitivity)
    • Analogy: Like a pilot constantly making small corrections to keep the airplane level
  • gain_schedule/ - The "smart adjuster"
    • Purpose: Automatically changes PID gains based on flight conditions (since rocket dynamics change dramatically during flight)
    • Key File: gain_schedule.hpp - Defines an interface for lookup tables or interpolation schemes that adjust controller parameters based on variables like thrust level or velocity
    • Analogy: Like shifting gears in a car - different flight phases need different control responses
  • state_machine/ - The flight phase manager
    • Purpose: Tracks what stage of flight the rocket is in (idle, armed, boost, coast, descent, etc.) and enables/disables appropriate behaviors
    • Key File: state_machine.hpp - Defines states and transition logic based on time, acceleration, altitude, and velocity
    • Analogy: Like a mission control flowchart that knows when to arm parachutes vs. when to ignite engines

Core Design Principles:

  • Dependency Injection: Core logic depends only on abstract HAL interfaces (never concrete hardware)
  • Platform Independence: Same core code runs on simulation, ESP32, STM32, etc.
  • Safety Features: Anti-windup, output limits, and reset mechanisms prevent dangerous states
  1. Hardware Abstraction Layer (hal/)

This is the "contract" between software and hardware - defines what the core expects from hardware without specifying how it's implemented.

Purpose: Provides pure C++ interfaces (abstract classes) for all hardware components. The core logic talks to these interfaces, while platform-specific implementations provide the concrete details.

Key Files:

  • imu.hpp - Inertial Measurement Unit interface
    • Purpose: Standardized way to read accelerometer, gyroscope, and (optionally) magnetometer data
    • Methods: initialize(), readAccelerometer(), readGyroscope(), etc.
  • servo.hpp - Servo motor control interface
    • Purpose: Standardized way to control the gimbals that tilt the rocket engine
    • Methods: initialize(), setAngle(), getAngle(), plus optional rate/torque controls
  • README.md - Documents the HAL pattern and lists other planned interfaces (Baro, Clock, Transport, Storage)

Key Benefit: Core logic remains unchanged when switching hardware platforms - only the HAL implementations need to change.

  1. Platform Implementations (platforms/)

This is where the "rubber meets the road" - platform-specific code that fulfills the HAL contracts.

Purpose: Contains concrete implementations of HAL interfaces for specific hardware platforms. Each subdirectory represents a supported board.

Current Structure:

  • esp32/ - ESP32 microcontroller implementations (WiFi/Bluetooth capable)
    • Subdirectories: src/ (source files), include/ (headers)
    • Status: Currently empty (awaiting implementation), but ready for ESP32-specific HAL implementations
  • stm32/ - Planned for STM32 microcontrollers (common in aerospace)
    • Status: Only exists as a placeholder directory

Implementation Requirements (from platforms/README.md):

  • Implement all pure virtual methods from HAL interfaces
  • Handle hardware initialization (clocks, peripherals, etc.)
  • Manage platform-specific details (register addresses, timing constraints)
  • Keep hardware details isolated from core logic

Workflow: When building for a specific platform, you include the corresponding platform's implementations alongside the core and HAL interfaces.

  1. Simulation (sim/)

This is the "wind tunnel" - lets you test and develop without risking actual hardware.

Purpose: Host-side simulation that runs the exact same core code as the target hardware, enabling safe, rapid iteration.

Key Subdirectories:

  • plant/ - Physics simulation (rigid body dynamics, thrust modeling)
    • Purpose: Simulates how the rocket vehicle responds to control inputs
  • sensor_models/ - Realistic sensor noise and error models
    • Purpose: Adds realistic imperfections to simulated sensor data (bias, noise, drift, etc.)
  • io/ - Simulated I/O interfaces (GUI, network, etc.)
    • Purpose: Mimics hardware communication channels for testing end-to-end flows

Key Benefits (from sim/README.md):

  • Test core logic without hardware risks
  • Rapid iteration and debugging (no flash/recompile cycle)
  • Automated testing capabilities
  • Hardware-in-the-loop (HIL) preparation

How It Works: The simulation replaces HAL implementations with simulated versions that feed virtual sensor data to the core, which then generates virtual actuator commands that update the simulated physics model.

  1. Tests (tests/)

This is the "quality control" - automated checks to ensure correctness.

Purpose: Contains unit tests for the core logic, running on host PC without hardware requirements.

Key Aspects (from tests/README.md):

  • Framework: Google Test (or similar C++ testing framework)
  • Isolation: Tests core logic in isolation by mocking HAL interfaces
  • Coverage:
    • test_estimator.cpp - Attitude estimation algorithms
    • test_pid.cpp - PID controller (including anti-windup)
    • test_gain_schedule.cpp - Thrust-curve gain scheduling
    • test_state_machine.cpp - Flight state machine transitions
  • Principles:
    • Mathematical correctness verification
    • Edge case and error condition testing
    • Deterministic behavior assurance
    • High test coverage for safety-critical code

Testing Flow:

  1. Build tests: make test (or ctest)

  2. Execute: ./tvc_tests

  3. Review console output or test reports

  4. Tools (tools/)

This is the "ground support equipment" - helper applications for development and operation.

Purpose: Contains scripts and applications that aid in development, debugging, and real-time interaction with the system.

Current Contents:

  • gui/ - Ground Control Station GUI
    • source.py / source.txt - Identical Python script implementing a graphical interface
    • Functionality:
      • Connects to ESP32 via TCP/IP (configurable IP/port)
      • Provides joystick-like pitch/yaw control via mouse drag
      • Throttle control via slider
      • Real-time telemetry display (pitch/yaw angles)
      • Sends formatted command packets to flight controller
    • Dependencies: customtkinter (modern Tkinter wrapper), standard library sockets
    • Analogy: Like Mission Control's console at Houston - lets engineers monitor and send commands to the spacecraft

Note: The .txt file appears to be a backup copy of the Python script.

  1. Documentation (docs/)

This is the "operator's manual" - essential reference for developers and contributors.

Purpose: Captures project conventions, communication protocols, and design decisions to ensure consistency.

Key Files:

  • conventions.md - Standardizes units, sign conventions, coordinate systems, and control loop rates
    • Critical Sections: Units (meters, seconds, newtons), sign conventions (to be defined), fixed 200Hz control loop
    • Purpose: Prevents costly misinterpretations (e.g., mixing radians/degrees or inconsistent axis definitions)
  • protocol.md - Defines the communication protocol between ground station, flight controller, and simulators
    • Key Aspects: Transport-agnostic framed messages, message types (telemetry/commands), implementation notes (little-endian, fixed-size fields)
    • Purpose: Ensures all components speak the same "language" regardless of underlying transport (UART, TCP/IP, CAN, etc.)
  1. Proposal (proposal/)

This is the "project genesis" - original planning and approval documents.

Purpose: Contains thesis proposal materials, concept art, and planning documents that preceded implementation.

Contents (from file listing):

  • Technical Diagrams: easyeda.png (circuit design), gsv_logo.ai/.png (logos), matlab.png (analysis plots)
  • Reference Images: nozzle.png, openrocket.png (inspiration/similar projects)
  • LaTeX Source: pro.tex (main document), plus auxiliary files (pro.aux, pro.log, pro.out, pro.pdf, pro.toc, pro.tex, pro.toc)
  • Bibliography: report.tex
  • Visual Assets: sf_1.jpeg, sf_2.png, sorbitol.jpeg, thrust_1.png
  • Purpose: Shows the evolutionary path from concept to implementation - valuable for thesis defense documentation
  1. Build System & Configuration

These files govern how the project is compiled and configured.

  • CMakeLists.txt - CMake build configuration
    • Purpose: Defines how to build the core library, tests, and examples across platforms
    • Benefit: Enables out-of-tree builds, dependency management, and platform-independent compilation
  • PlatformIO.ini - PlatformIO configuration for embedded development
    • Purpose: Specifies build environments, dependencies, and upload settings for platforms like ESP32
    • Benefit: Simplifies embedded development with pre-configured toolchains and library management
  • README.md - Project overview (already reviewed)
    • Purpose: High-level project description, goals, and conceptual design images
  1. Version Control & Generated Files

These support development but aren't part of the source logic.

  • build/ - Directory containing compiled objects, executables, and libraries
    • Note: Generated by the build process; safe to delete and regenerate
  • .git/ - Git version control database
    • Purpose: Tracks all changes to the source code over time
    • Note: Managed by Git; users typically interact via git commands rather than accessing directly

Development Workflow Summary

Here's how the pieces fit together in practice:

  1. Design Phase:
    • Work in core/ to implement/improve algorithms (estimator, PID, gain schedule, state machine)
    • Update docs/ with any new conventions or protocol changes
  2. Implementation Phase:
    • Create/update HAL implementations in platforms/<your_platform>/
    • Ensure all pure virtual methods are implemented
  3. Validation Phase:
    • Test in sim/ first (safe, fast iteration)
    • Run unit tests in tests/ to catch regressions
    • Deploy to actual hardware using tools/gui/source.py for real-time monitoring
  4. Documentation Phase:
    • Update docs/ with any new findings
    • Keep proposal/ as historical record of project origins

This structure allows you to develop, test, and deploy the TVC system with confidence that the core logic remains consistent across simulation, testing, and flight hardware.


Key Takeaways for Your Thesis Defense

When explaining this to your review board, emphasize:

  1. Separation of Concerns: Core logic (math/control) is completely decoupled from hardware specifics
  2. Portability: Same core code runs on simulation, ESP32, future STM32, etc.
  3. Safety-First Design: Anti-windup, output limits, and state machines prevent dangerous conditions
  4. Professional Practices: Unit testing, simulation validation, and clear documentation
  5. Systems Thinking: Considers sensors, control law, actuators, and flight phases as an integrated system

This architecture isn't just for rockets - it's a template for any embedded control system requiring precision, safety, and adaptability. Good luck with your defense! 🚀