{"owner":"MarlinFirmware","repo":"Marlin","hasSkills":true,"hasMcp":false,"mcpConfig":null,"found":["AGENTS.md"],"skills":{"AGENTS.md":"# Marlin 3D Printer Firmware\n\n> This file consolidates the project summary (`docs/project-summary.md`) into the top-level agent reference. It is the canonical orientation document for the whole repo. Per-HAL working notes live in `Marlin/src/HAL/<FAMILY>/AGENTS.md` (e.g. `Marlin/src/HAL/AT32/AGENTS.md`).\n\n## 1. Executive Summary\n\nMarlin is an open-source firmware for 3D printers, written in C/C++ and built on the Arduino framework via PlatformIO. It sits between a host computer (running slicer software) and the printer's hardware, translating G-code movement commands into precise stepper motor control, temperature regulation, and peripheral management. The firmware supports 15+ microcontroller platforms (STM32, AVR, ESP32, RP2040, and more), 400+ pin configuration files across 24 board families, and a modular feature system with 80+ enable/disable features. At over 2,500 source files, Marlin is one of the most widely deployed 3D printer firmware projects in the world, licensed under GPL v3.0.\n\n## 2. Architecture Overview\n\nMarlin follows a layered embedded firmware architecture organized around a Hardware Abstraction Layer (HAL), a G-code command processing pipeline, a set of core motion/thermal modules, and a rich feature system. The firmware's singleton entry point is the `Marlin` class (`MarlinCore`), which manages global state and the main control loop.\n\n```mermaid\ngraph TB\n    subgraph Environment[\"Printer Environment\"]\n        Host[\"Host Computer\\n(Slicer / Host Software)\"]\n        SD[\"SD Card\\n(SdFat)\"]\n        Sensors[\"Thermistors &\\nEndstops\"]\n        Motors[\"Stepper Motors\\n&amp; Drivers\"]\n        Heaters[\"Heaters &amp; Fans\"]\n        Display[\"LCD / TFT / DWIN\"]\n    end\n\n    subgraph Marlin[\"Marlin Firmware\"]\n        subgraph GCode[\"G-Code Subsystem\"]\n            Queue[\"GCodeQueue\\nRing Buffer\"]\n            Parser[\"GCodeParser\\nParameter Extraction\"]\n            Suite[\"GcodeSuite\\nCommand Dispatcher\"]\n        end\n        subgraph Modules[\"Core Modules\"]\n            Motion[\"Motion Planner\"]\n            Planner[\"Block Planner\"]\n            Stepper[\"Stepper Driver\"]\n            Temp[\"Temperature Manager\"]\n        end\n        subgraph Features[\"Feature System\\n80+ modules\"]\n            BedLevel[\"Bed Leveling\"]\n            PowerLoss[\"Power Loss Recovery\"]\n            Runout[\"Filament Runout\"]\n            MMU[\"Multi-Material\\nUnit\"]\n        end\n        subgraph HAL[\"Hardware Abstraction Layer\"]\n            Shared[\"HAL Shared Code\"]\n            Platforms[\"15+ Platform HALs\"]\n        end\n    end\n\n    Host -->|\"USB Serial\\n250k baud\"| Suite\n    SD -->|\"SD Interface\"| Queue\n    Suite --> Parser\n    Parser --> Suite\n    Queue --> Suite\n    Suite --> Motion\n    Suite --> Temp\n    Motion --> Planner\n    Planner --> Stepper\n    Stepper --> Motors\n    Temp --> Heaters\n    Temp --> Sensors\n    Display <-->|\"SPI/I2C/UART\"| Suite\n```\n\nThe firmware communicates with the host via serial at 250,000 baud (configurable), receiving G-code commands line-by-line. Commands are queued in a circular buffer (`GCodeQueue::ring_buffer`), parsed by `GCodeParser`, and dispatched by `GcodeSuite` to category-specific handlers (motion, temperature, configuration, calibration, etc.). The core modules handle the low-level real-time tasks: the planner generates motion blocks with jerk control and acceleration profiling, the stepper driver issues pulse trains, and the temperature manager runs PID loops on thermistor inputs.\n\n### Supported Hardware Platforms\n\n| Platform Family | MCUs | Architecture | Notes |\n| --- | --- | --- | --- |\n| STM32 (various) | STM32F0, F1, F4, F7, H7, G0 | ARM Cortex-M | Primary 32-bit target |\n| AVR | ATmega2560, ATmega1280, AT90USB | 8-bit AVR | Legacy support |\n| ESP32 | ESP32-S3, ESP32-S2 | Xtensa/RISC-V | WiFi/BLE capability |\n| SAMD | SAMD21, SAMD51 | ARM Cortex-M0+/M4 | Adafruit Feather M4 |\n| RP2040 | RP2040, RP2350 | ARM Cortex-M33 | Raspberry Pi Pico |\n| LPC | LPC1768, LPC1769 | ARM Cortex-M3 | RAMBo, Melzi boards |\n| GD32 | GD32F1, GD32F3 | ARM Cortex-M3 | GigaDevice clones |\n| HC32 | HC32F4 | ARM Cortex-M4 | JCEC chips |\n| AT32 | AT32F4 | ARM Cortex-M4 | Artery Tek |\n| Teensy | 3.1/3.2, 3.5/3.6, 4.0/4.1 | ARM Cortex-M4/M7 | PJRC boards |\n| Linux Simulator | x86/x64 | Native | CI/testing |\n| Native Simulator | Any | Native | Unit testing |\n\n## 3. Processing Pipeline\n\nThe G-code processing pipeline follows a well-defined flow from input ingestion through parsing, dispatch, and hardware actuation.\n\n```mermaid\nflowchart TD\n    InputSerial[\"Serial Input\\nUSB / UART\"] --> Queue\n    InputSD[\"SD Card\\nSdFat\"] --> Queue\n    InputProgmem[\"Program Memory\\nPROGMEM\"] --> Queue\n\n    Queue[\"GCodeQueue\\nRing Buffer\\nBUFSIZE entries\"] --> Parser\n\n    Parser[\"GCodeParser\\n• Letter/Code/Subcode\\n• Parameter extraction\\n• FASTER_GCODE_PARSER\\n  pre-scanned flags\"] --> Suite\n\n    Suite[\"GcodeSuite\\nCommand Dispatcher\\n• Subcommand routing\\n• Parameter validation\\n• Endstop events\"]\n\n    Suite --> CatMotion[\"Motion\\nG0/G1/G2/G3\"]\n    Suite --> CatTemp[\"Temperature\\nM104/M105/M106/M107/M109\"]\n    Suite --> CatConfig[\"Configuration\\nM200-M205/M301/M92\"]\n    Suite --> CatCalibrate[\"Calibration\\nG28/G33/G34/G425\"]\n    Suite --> CatSD[\"SD Card\\nM20-M34/M928\"]\n\n    CatMotion --> Planner\n    CatTemp --> Temp\n    CatCalibrate --> Motion\n\n    Planner[\"Block Planner\\n• Trapezoidal profile\\n• Jerk control\\n• Buffer: BLOCK_BUFFER_SIZE\"] --> Stepper\n    Motion[\"Motion\\n• axis_position()\\n• relative_mode\\n• dual_x_carriage\"] --> Planner\n    Temp[\"Temperature\\n• PID loops\\n• thermistor tables\\n• safety checks\"] --> Heaters\n\n    Stepper[\"Stepper Driver\\n• issue_pending()\\n• TMC SPI config\\n• Trinamic drivers\"] --> Output[\"Hardware Outputs\\n• Step/Dir pulses\\n• PWM heat/fan\\n• Serial responses\"]\n```\n\n### Key Pipeline Components\n\n**GCodeQueue** — A circular ring buffer (`RingBuffer`) that holds up to `BUFSIZE` G-code command strings. Commands enter via three injectors: serial input (USB/UART), SD card file reading, and in-firmware injected commands (PROGMEM). The queue's `advance()` method pops the next command and hands it to the parser.\n\n**GCodeParser** — Parses a single G-code line, extracting the command letter (G/M/T), code number, subcode, and all parameter values (X, Y, Z, E, F, S, P, etc.). When `FASTER_GCODE_PARSER` is enabled, the parser pre-scans all parameters into a flags array for O(1) lookups.\n\n**GcodeSuite** — The command dispatcher singleton. Each G/M code maps to a handler method within this class. Commands are routed to category subdirectories under `src/gcode/` (e.g., `motion/`, `temp/`, `config/`, `calibrate/`). The suite also handles pre- and post-command hooks for endstop events, buffer monitoring, and inactivity shutdown.\n\n## 4. Core Components\n\n### 4.1 Firmware Entry Point\n\nThe firmware lifecycle is managed by `MarlinCore.cpp` (~1,777 lines), structured around Arduino's `setup()` and `loop()` functions:\n\n- **`setup()`** — Initializes HAL pins, serial ports, all modules (stepper, temperature, motion, planner, settings), features (runout detection, power loss recovery, LEDs), and the UI subsystem. Each initialization block is wrapped in `SETUP_RUN()` for debug logging in dev mode.\n- **`loop()`** — Runs continuously (infinite loop on AVR, structured loop on 32-bit platforms). Each iteration calls `marlin.idle()`, processes the G-code queue, checks power-off timers, and handles endstop events.\n\n### 4.2 Singleton Architecture\n\nGlobal state is managed through singletons:\n\n| Singleton | File | Responsibility |\n| --- | --- | --- |\n| `marlin` | `MarlinCore.cpp/h` | Global state machine, inactivity management, kill/suicide, heatup waits |\n| `gcode` | `gcode/gcode.cpp` | G-code command dispatch |\n| `queue` | `gcode/queue.h` | Command queue ring buffer |\n| `planner` | `module/planner.cpp` | Motion block buffer and trapezoidal profiling |\n| `stepper` | `module/stepper.cpp` | Step pulse generation and TMC driver config |\n| `thermalManager` | `module/temperature.cpp` | PID loops, thermistor reading, safety monitoring |\n| `card` | `sd/cardreader.cpp` | SD card file system operations |\n| `ui` | `lcd/marlinui.cpp/h` | LCD/UI state machine and menu system |\n\n### 4.3 Module System\n\nThe `module/` directory contains the core motion and thermal management classes:\n\n| Module | File | Description |\n| --- | --- | --- |\n| **Motion** | `motion.h/cpp` | High-level axis positioning, coordinate transforms, joint interpolation |\n| **Planner** | `planner.h/cpp` | Block buffer, trapezoidal velocity profiling, junction deviation |\n| **Stepper** | `stepper.h/cpp` | Step pulse generation, direction control, TMC Trinamic SPI configuration |\n| **Temperature** | `temperature.h/cpp` | PID autotune (M303), thermistor tables, hotend/bed/heater management |\n| **Endstops** | `endstops.h/cpp` | Endstop interrupt handling, homing logic, soft endstops |\n| **Probe** | `probe.h/cpp` | Bed probing (G30, G31/G32, G38, bltouch), Z-offset management |\n| **Settings** | `settings.h/cpp` | EEPROM persistence, configuration storage and retrieval |\n| **PrintCounter** | `printcounter.h/cpp` | Print time, filament usage, and job statistics |\n| **Servo** | `servo.h/cpp` | Servo control for solenoids, lid mechanisms |\n| **Delta/Scara/Polar** | `delta.h`, `scara.h`, `polar.h` | Kinematic transforms for non-Cartesian printers |\n| **Tool Change** | `tool_change.h/cpp` | Multi-extruder tool switching, hotend offset, PTFE purge |\n\n### 4.4 Feature System\n\nThe `feature/` directory contains 80+ optional modules, each gated by a `#if ENABLED(FEATURE_NAME)` preprocessor check:\n\n**Motion Features:** Linear Advance (`linearadvance`), Pressure Advance, Adaptive Multi-Axis Stepping, Direct Stepping, Bresenham acceleration, Resonance Compensation, X-Axis Twist Correction, Z-Stepper Alignment, Backlash Compensation.\n\n**Thermal Features:** Automatic PID Tuning (M303), Thermal Protection, Probe Temperature Compensation, Mixed Extruder (`mixing`), Bowden/Direct Drive Retraction (`fwretract`).\n\n**Peripheral Features:** Power Loss Recovery (`powerloss`), Filament Runout Detection (`runout`), Ethernet Connectivity (`ethernet`), RS485 Communication (`rs485`), MMU/Multi- Material Unit (`mmu`, `mmu3`), Solenoid Control (`solenoid`), Spindle/Laser (`spindle_laser`), Case Lights (`caselight`), LED Color Control (`leds`).\n\n**UI Features:** Touch Screen (`touch`), LVGL TFT UI (`mks_ui`), DWIN Display (`dwin`), Extensible UI (`extui`), Password Protection (`password`), Joystick Input (`joystick`).\n\n**Bed Leveling:** Unified Bed Leveling (UBL), Manual Bed Leveling (MBL), Automatic Bed Leveling (ABL), G26 Mesh Validation, G35 Auto Bed Leveling, Bed Level Visualizer.\n\n## 5. G-Code Command Reference\n\nMarlin implements 100+ G-code commands organized into 14 categories under `src/gcode/`:\n\n| Category | Directory | Key Commands | Description |\n| --- | --- | --- | --- |\n| **Motion** | `motion/` | G0, G1, G2, G3, G5, G6, G80, M400, M290 | Linear/arc moves, rapid moves, dwell, wait, jog |\n| **Temperature** | `temp/` | M104/M105/M106/M107/M109, M140/M190, M303 | Hotend/bed temp set/read, fan control, PID autotune |\n| **Configuration** | `config/` | M200-M205, M301, M92, M43, M218, M217 | Extruder steps, accel/jerk, PID, hotend offset, bowden length |\n| **Calibration** | `calibrate/` | G28, G33, G34, G425, M48, M566, M665 | Home, delta calibration, nozzle purge, backlash, bellows |\n| **Geometry** | `geometry/` | G17-G19, G53-G59, G92, M206, M428 | Plane selection, coordinate systems, position reset, offsets |\n| **Control** | `control/` | M17/M18/M84, M80/M81, M3-M5, M7-M9, T | Enable axes, power, spindle, tool select, feedrate/extruder units |\n| **Probe** | `probe/` | G30, G31/G32, G38, M851, M401/M402, M102 | Bed probe, probe type, probe actions |\n| **SD Card** | `sd/` | M20-M34, M928, M1001, M1003 | File listing, select, start, stop, abort, load, save |\n| **LCD** | `lcd/` | M0, M1, M73, M117, M145, M250, M300 | Pause, progress, message, color, beep |\n| **Host** | `host/` | M16, M110, M113, M114, M115, M118, M119, M154, M360, M876 | Line numbers, machine info, endstop report, kinematic config |\n| **EEPROM** | `eeprom/` | M500, M501, M502, M503, M504 | Save/load/reset/settings EEPROM operations |\n| **Stats** | `stats/` | M31, M75-M78 | Print time, filament used, errors, buffer stats |\n| **Units** | `units/` | G20/G21, M82/M83, M149 | mm/inch, extrusion mode, temp unit display |\n| **OTA** | `ota/` | M936 | Over-the-air firmware update |\n\n## 6. Infrastructure & Deployment\n\n### 6.1 Build System\n\nMarlin uses PlatformIO as its primary build system, configured via `platformio.ini`:\n\n- **Framework**: Arduino (via PlatformIO)\n- **Build flags**: `-g3 -D__MARLIN_FIRMWARE__ -DNDEBUG -fsingle-precision-constant`\n- **Source filter**: Dynamic inclusion/exclusion of files based on target board via pre-build scripts (`configuration.py`, `common-dependencies.py`, `preflight-checks.py`)\n- **Include directory**: `Marlin/src/`\n- **Board definitions**: Custom PlatformIO board definitions in `buildroot/share/PlatformIO/boards/`\n\n### 6.2 Configuration System\n\nConfiguration is managed through a layered preprocessor conditional system:\n\n1. **`Configuration.h`** — User-editable hardware and feature configuration\n2. **`Configuration_adv.h`** — Advanced/experimental feature toggles\n3. **`Version.h`** — Build version, machine name, website URL\n4. **`inc/Conditionals-*.h`** — Auto-generated feature flags derived from Configuration.h\n5. **`inc/MarlinConfig.h`** — Prefix header including all conditionals, types, and sanity checks\n\nThe conditional system ensures that only enabled features compile, minimizing firmware footprint for resource-constrained 8-bit platforms.\n\n### 6.3 CI/CD Pipeline\n\nGitHub Actions workflows run on every pull request and push:\n\n| Workflow | Purpose |\n| --- | --- |\n| `ci-build-tests.yml` | Compiles Marlin for all supported boards (matrix strategy) |\n| `ci-unit-tests.yml` | Runs C++ unit tests on the native simulator |\n| `ci-validate-boards.yml` | Validates board pin configurations |\n| `ci-validate-pins.yml` | Checks for missing/invalid pin definitions |\n| `ci-validate-lines.yml` | Validates line count limits for 8-bit boards |\n| `auto-label.yml` | Auto-labels PRs by changed paths |\n| `check-pr.yml` | PR quality checks |\n\n### 6.4 Docker Build Environment\n\nA Dockerfile (`docker/Dockerfile`) provides a reproducible build environment:\n\n```dockerfile\nFROM python:3.11-bookworm\nRUN pip install -U platformio PyYaml\nRUN pio upgrade --dev\nWORKDIR /code\n```\n\n### 6.5 Testing\n\n- **Unit tests**: Located in `Marlin/tests/`, run via the Linux native simulator HAL\n- **Build tests**: CI compiles against 20+ board targets to catch compile errors\n- **Pin validation**: Automated checks for pin conflicts and missing definitions\n- **SdFat**: Integrated SdFat library for SD card file operations (Sd2Card, SdBaseFile, SdVolume)\n\n## 7. Extension Patterns\n\n### 7.1 Adding a New Feature\n\n1. Create your feature files in `Marlin/src/feature/` (e.g., `my_feature.h` and `my_feature.cpp`)\n2. Add `#define MY_FEATURE` to `Configuration_adv.h`\n3. The conditional system in `inc/Conditionals-*.h` will auto-generate `HAS_MY_FEATURE`\n4. Use `#if ENABLED(MY_FEATURE)` guards in your code\n5. Include your header from `MarlinCore.cpp` under the appropriate `#if ENABLED()` block\n6. Register G-code handlers in `gcode/gcode.cpp` or a new category subdirectory\n\n### 7.2 Adding a New G-Code Command\n\n1. Create a new file in the appropriate `src/gcode/<category>/` directory (e.g., `M1000.cpp`)\n2. Implement the handler method in the `GcodeSuite` class\n3. Register the command in the `process_commands()` method of `GcodeSuite`\n4. The command will be dispatched automatically when the parser encounters the letter/code\n\n### 7.3 Adding Board Support\n\n1. Create a new PlatformIO board definition in `buildroot/share/PlatformIO/boards/`\n2. Add pin definitions in `Marlin/src/pins/<family>/pins_<board>.h`\n3. If the MCU is new, add HAL support in `Marlin/src/HAL/<MCU_FAMILY>/`\n4. Update `ini/<platform>.ini` in `platformio.ini`'s `extra_configs`\n5. Run `ci-validate-pins.yml` to verify pin assignments\n\n### 7.4 Adding a Display Backend\n\n1. Create backend files in `Marlin/src/lcd/<backend>/`\n2. Implement the required display interface (SPI/I2C/UART)\n3. Add `#define ULTIPANEL` or display-specific `#define` to `Configuration.h`\n4. The LCD subsystem routes through `MarlinUI` to the appropriate backend\n\n## 8. Rules & Anti-Patterns\n\n### Best Practices\n\n- **Conditional compilation**: Always gate platform-specific code with `#if ENABLED()` or `#ifdef ARDUINO_ARCH_XXX`\n- **PROGMEM usage**: Store large strings and lookup tables in program memory on 8-bit platforms\n- **Interrupt safety**: Use `WAIT`/`NOOP` patterns for stepper ISR synchronization\n- **EEPROM limits**: Respect memory constraints — 8-bit boards have limited EEPROM (4KB-8KB)\n- **Thread safety**: The main loop and stepper ISR share state — use volatile and careful locking\n- **Static analysis**: Use `bug_on()` macros for compile-time assertion checks\n- **Code size**: 8-bit targets (AVR) have strict flash limits — enable only necessary features\n\n### Anti-Patterns\n\n- **Don't add features to `Configuration.h`** — use `Configuration_adv.h` for advanced/experimental features\n- **Don't modify HAL shared code** without understanding platform implications\n- **Don't use floating-point on AVR** without explicit `float` typing — the compiler defaults to single precision\n- **Don't block in the main loop** — all long operations must yield to `idle()` or use non-blocking patterns\n- **Don't assume 32-bit semantics** — code must compile for both 8-bit AVR and 32-bit ARM\n- **Don't hardcode pin numbers** — always use the pin definition headers\n\n## 9. Dependencies\n\n### Build Tools\n\n| Dependency       | Version           | Purpose                    |\n| ---------------- | ----------------- | -------------------------- |\n| PlatformIO       | Latest dev        | Build system and framework |\n| Arduino Core     | Platform-specific | Microcontroller SDK        |\n| GCC ARM Embedded | 12.x              | ARM cross-compiler         |\n| avr-gcc          | 7.x               | AVR cross-compiler         |\n\n### Libraries (integrated)\n\n| Library    | Purpose                                             |\n| ---------- | --------------------------------------------------- |\n| SdFat      | SD card file system (Sd2Card, SdBaseFile, SdVolume) |\n| u8glib     | OLED/LCD display driver (embedded in HAL)           |\n| LVGL       | TFT graphical UI (optional, for MKS UI)             |\n| heatshrink | G-code decompression for SD prints                  |\n\n### Platform Libraries\n\n| Platform | Libraries                     |\n| -------- | ----------------------------- |\n| STM32    | STM32 HAL/LL, STM32duino core |\n| AVR      | Arduino AVR core, TimerOne    |\n| ESP32    | ESP-IDF components, WiFi      |\n| RP2040   | Arduino RP2040 core, PIOasm   |\n| Teensy   | Teensyduino core, Bounce2     |\n| SAMD     | Arduino SAMD core             |\n\n## 10. Code Structure\n\n```\nMarlinFirmware/                  # Repo root (this directory). `cd` here for PlatformIO builds.\n├── Marlin/                      # The Arduino \"sketch\" (application source + config files)\n│   ├── Configuration.h          # User hardware configuration\n│   ├── Configuration_adv.h      # Advanced/experimental toggles\n│   ├── Marlin.ino               # Board-specific entry stub\n│   ├── Makefile                 # Alternative build (simulator)\n│   ├── Version.h                # Build version, machine name\n│   ├── config.ini               # PlatformIO extra config\n│   ├── lib/                     # Integrated libraries\n│   └── src/                     # Application source (see below)\n├── buildroot/                   # Build infrastructure\n├── ini/                         # PlatformIO platform configs\n├── docs/                        # Project documentation\n├── docker/                      # Docker build environment\n├── .github/workflows/           # CI/CD pipelines\n└── platformio.ini               # Main PlatformIO configuration\n```\n\n### Marlin/src layout\n\n```\nMarlin/src/\n├── MarlinCore.cpp/h         # Firmware entry, setup(), loop(), Marlin singleton\n├── core/                    # Core utilities (serial, language, types, mstring)\n│   ├── gcode/                   # G-code subsystem\n│   │   ├── gcode.cpp/h          # GcodeSuite dispatcher\n│   │   ├── parser.cpp/h         # GCodeParser\n│   │   ├── queue.cpp/h          # GCodeQueue ring buffer\n│   │   ├── motion/              # G0-G6, M290, M400\n│   │   ├── temp/                # M104-M109, M140-M193, M303\n│   │   ├── config/              # M200-M205, M301, M92, M218\n│   │   ├── calibrate/           # G28, G33, G34, G425, M48\n│   │   ├── bedlevel/            # G26, G35, G42, M420\n│   │   ├── geometry/            # G17-G19, G53-G59, G92\n│   │   ├── probe/               # G30-G38, M851, M401\n│   │   ├── sd/                  # M20-M34, M928\n│   │   ├── lcd/                 # M0, M1, M73, M117\n│   │   ├── host/                # M16, M110-M119\n│   │   ├── eeprom/              # M500-M504\n│   │   ├── stats/               # M31, M75-M78\n│   │   ├── units/               # G20/G21, M82/M83\n│   │   └── control/             # M3-M5, M7-M9, M17-M85, T\n│   ├── module/                  # Core modules\n│   │   ├── motion.h/cpp         # Axis positioning, kinematics\n│   │   ├── planner.h/cpp        # Block buffer, trapezoidal profiling\n│   │   ├── stepper.h/cpp        # Step pulses, TMC drivers\n│   │   ├── temperature.h/cpp    # PID, thermistors, safety\n│   │   ├── endstops.h/cpp       # Endstop interrupts, homing\n│   │   ├── probe.h/cpp          # Bed probing, Z-offset\n│   │   ├── settings.h/cpp       # EEPROM persistence\n│   │   ├── delta.h/cpp          # Delta kinematics\n│   │   ├── scara.h/cpp          # Scara kinematics\n│   │   ├── polar.h/cpp          # Polar kinematics\n│   │   ├── polargraph.h/cpp     # Polar graph kinematics\n│   │   ├── servo.h/cpp          # Servo control\n│   │   ├── printcounter.h/cpp   # Print statistics\n│   │   ├── tool_change.h/cpp    # Multi-extruder switching\n│   │   ├── ft_motion/           # Fine-tune motion\n│   │   └── stepper/             # Stepper internals, Trinamic\n│   ├── feature/                 # 80+ optional features\n│   │   ├── bedlevel/            # UBL, MBL, ABL\n│   │   ├── leds/                # LED color control\n│   │   ├── mmu/                 # Multi-material unit\n│   │   ├── mmu3/                # MMU3 variant\n│   │   ├── powerloss.h/cpp      # Power loss recovery\n│   │   ├── runout.h/cpp         # Filament runout detection\n│   │   ├── pause.h/cpp          # Pause/resume\n│   │   ├── mixing.h/cpp         # Mixed extruder\n│   │   ├── fwretract.h/cpp      # Firmware retraction\n│   │   ├── resonance/           # Resonance compensation\n│   │   ├── spindle_laser.h/cpp  # Spindle/laser control\n│   │   ├── ethernet.h/cpp       # Ethernet connectivity\n│   │   ├── solenoid.h/cpp       # Solenoid control\n│   │   ├── password/            # Password protection\n│   │   ├── joystick.h/cpp       # Joystick input\n│   │   ├── tmc_util.h/cpp       # TMC driver utilities\n│   │   └── ...                  # 60+ more features\n│   ├── lcd/                     # Display/UI subsystem\n│   │   ├── marlinui.h/cpp        # Main UI controller\n│   │   ├── HD44780/             # Hitachi HD44780 LCD\n│   │   ├── dogm/                # DOGM OLED/LCD\n│   │   ├── tft/                 # TFT displays\n│   │   ├── tft_io/              # TFT I/O drivers\n│   │   ├── dwin/                # DWIN displays\n│   │   ├── extui/               # Extensible UI (MKS LVGL)\n│   │   ├── menu/                # Menu system\n│   │   ├── touch/               # Touch screen\n│   │   ├── language/            # Multi-language strings\n│   │   └── sovol_rts/           # Sovol RTS display\n│   ├── libs/                    # Utility libraries\n│   │   ├── bresenham.h          # Bresenham line algorithm\n│   │   ├── vector_3.h/cpp       # 3D vector math\n│   │   ├── circularqueue.h      # Generic circular queue\n│   │   ├── adc/                 # ADC utilities\n│   │   ├── heatshrink/          # Decompression\n│   │   ├── nozzle.cpp/h         # Nozzle cleaning\n│   │   ├── numtostr.h/cpp       # Number-to-string\n│   │   ├── hex_print.h/cpp      # Hex printing\n│   │   ├── crc16.h/cpp          # CRC-16 calculation\n│   │   ├── stopwatch.h/cpp      # Stopwatch utility\n│   │   ├── least_squares_fit.h  # Least squares fitting\n│   │   └── ...                  # 15+ utility libs\n│   ├── sd/                      # SD card subsystem\n│   │   ├── cardreader.h/cpp     # Card reader interface\n│   │   ├── SdFat*               # SdFat library (file system)\n│   │   ├── disk_io_driver.h     # Disk I/O abstraction\n│   │   └── usb_flashdrive/      # USB flash drive support\n│   ├── pins/                    # Pin definitions (400+ files)\n│   │   ├── pins.h               # Pin inclusion router\n│   │   ├── ramps/               # Ramps board family\n│   │   ├── mega/                # Mega board family\n│   │   ├── rambo/               # Rambo board family\n│   │   ├── sanguino/            # Sanguino board family\n│   │   ├── stm32f1/             # STM32F1 boards\n│   │   ├── stm32f4/             # STM32F4 boards\n│   │   ├── stm32f7/             # STM32F7 boards\n│   │   ├── stm32h7/             # STM32H7 boards\n│   │   ├── stm32g0/             # STM32G0 boards\n│   │   ├── stm32f0/             # STM32F0 boards\n│   │   ├── sam/                 # SAM boards\n│   │   ├── samd/                # SAMD boards\n│   │   ├── rp2040/              # RP2040 boards\n│   │   ├── lpc1768/             # LPC1768 boards\n│   │   ├── lpc1769/             # LPC1769 boards\n│   │   ├── teensy2/             # Teensy 2.x boards\n│   │   ├── teensy3/             # Teensy 3.x boards\n│   │   ├── teensy4/             # Teensy 4.x boards\n│   │   ├── esp32/               # ESP32 boards\n│   │   ├── gd32f1/              # GD32F1 boards\n│   │   ├── gd32f3/              # GD32F3 boards\n│   │   ├── hc32f4/              # HC32F4 boards\n│   │   ├── at32f4/              # AT32F4 boards\n│   │   └── native/              # Native/simulator\n│   ├── HAL/                     # Hardware Abstraction Layer\n│   │   ├── HAL.h                # HAL interface definition\n│   │   ├── platforms.h          # Platform selection\n│   │   ├── shared/              # Cross-platform HAL code\n│   │   │   ├── HAL.cpp/h        # Shared HAL implementation\n│   │   │   ├── Delay.h          # Safe delay function\n│   │   │   ├── eeprom_api.h     # EEPROM API\n│   │   │   ├── cpu_exception/   # Exception handling\n│   │   │   └── backtrace/       # Stack backtrace\n│   │   ├── STM32/               # STM32 platform HAL\n│   │   ├── AVR/                 # AVR platform HAL\n│   │   ├── ESP32/               # ESP32 platform HAL\n│   │   ├── DUE/                 # Arduino Due HAL\n│   │   ├── SAMD21/              # SAMD21 HAL\n│   │   ├── SAMD51/              # SAMD51 HAL\n│   │   ├── RP2040/              # RP2040 HAL\n│   │   ├── LPC1768/             # LPC1768 HAL\n│   │   ├── GD32_MFL/            # GD32 HAL\n│   │   ├── HC32/                # HC32 HAL\n│   │   ├── AT32/                # AT32 HAL\n│   │   ├── TEENSY31_32/         # Teensy 3.1/3.2 HAL\n│   │   ├── TEENSY35_36/         # Teensy 3.5/3.6 HAL\n│   │   ├── TEENSY40_41/         # Teensy 4.0/4.1 HAL\n│   │   ├── STM32F1/             # STM32F1 HAL\n│   │   ├── LINUX/               # Linux simulator HAL\n│   │   └── NATIVE_SIM/          # Native simulator HAL\n│   └── tests/                   # Unit tests\n│       ├── unit_tests.h/cpp     # Test suite\n│       └── *.ini                # Test configurations\n├── docs/                        # Project documentation\n│   ├── AGENTS.md                # This document\n│   └── diagrams/                # Architecture diagrams\n│       ├── high-level-architecture.drawio\n│       ├── processing-pipeline.drawio\n│       └── component-relationships.drawio\n├── buildroot/                   # Build infrastructure\n│   ├── share/PlatformIO/        # PlatformIO board definitions & scripts\n│   ├── test-gcode/              # G-code test files\n│   └── tests/                   # Build test configurations\n├── ini/                         # PlatformIO platform configs\n│   ├── avr.ini, due.ini, esp32.ini\n│   ├── stm32-common.ini, stm32f1.ini, stm32f4.ini\n│   ├── stm32f7.ini, stm32h7.ini, stm32g0.ini\n│   ├── samd21.ini, samd51.ini\n│   ├── raspberrypi.ini, teensy.ini\n│   ├── at32.ini, gd32.ini, hc32.ini\n│   ├── lpc176x.ini, native.ini\n│   ├── features.ini, renamed.ini\n│   └── stm32f1-maple.ini\n├── test/                        # Root-level test configurations\n├── docker/                      # Docker build environment\n├── .github/workflows/           # CI/CD pipelines\n└── platformio.ini               # Main PlatformIO configuration\n```\n\n---\n\n_This document was consolidated from `docs/project-summary.md` into the top-level `AGENTS.md` on 2026-07-11 to serve as the canonical repo orientation reference. It reflects the codebase as of the bugfix-2.1.x branch._\n"},"files":{"AGENTS.md":"# Marlin 3D Printer Firmware\n\n> This file consolidates the project summary (`docs/project-summary.md`) into the top-level agent reference. It is the canonical orientation document for the whole repo. Per-HAL working notes live in `Marlin/src/HAL/<FAMILY>/AGENTS.md` (e.g. `Marlin/src/HAL/AT32/AGENTS.md`).\n\n## 1. Executive Summary\n\nMarlin is an open-source firmware for 3D printers, written in C/C++ and built on the Arduino framework via PlatformIO. It sits between a host computer (running slicer software) and the printer's hardware, translating G-code movement commands into precise stepper motor control, temperature regulation, and peripheral management. The firmware supports 15+ microcontroller platforms (STM32, AVR, ESP32, RP2040, and more), 400+ pin configuration files across 24 board families, and a modular feature system with 80+ enable/disable features. At over 2,500 source files, Marlin is one of the most widely deployed 3D printer firmware projects in the world, licensed under GPL v3.0.\n\n## 2. Architecture Overview\n\nMarlin follows a layered embedded firmware architecture organized around a Hardware Abstraction Layer (HAL), a G-code command processing pipeline, a set of core motion/thermal modules, and a rich feature system. The firmware's singleton entry point is the `Marlin` class (`MarlinCore`), which manages global state and the main control loop.\n\n```mermaid\ngraph TB\n    subgraph Environment[\"Printer Environment\"]\n        Host[\"Host Computer\\n(Slicer / Host Software)\"]\n        SD[\"SD Card\\n(SdFat)\"]\n        Sensors[\"Thermistors &\\nEndstops\"]\n        Motors[\"Stepper Motors\\n&amp; Drivers\"]\n        Heaters[\"Heaters &amp; Fans\"]\n        Display[\"LCD / TFT / DWIN\"]\n    end\n\n    subgraph Marlin[\"Marlin Firmware\"]\n        subgraph GCode[\"G-Code Subsystem\"]\n            Queue[\"GCodeQueue\\nRing Buffer\"]\n            Parser[\"GCodeParser\\nParameter Extraction\"]\n            Suite[\"GcodeSuite\\nCommand Dispatcher\"]\n        end\n        subgraph Modules[\"Core Modules\"]\n            Motion[\"Motion Planner\"]\n            Planner[\"Block Planner\"]\n            Stepper[\"Stepper Driver\"]\n            Temp[\"Temperature Manager\"]\n        end\n        subgraph Features[\"Feature System\\n80+ modules\"]\n            BedLevel[\"Bed Leveling\"]\n            PowerLoss[\"Power Loss Recovery\"]\n            Runout[\"Filament Runout\"]\n            MMU[\"Multi-Material\\nUnit\"]\n        end\n        subgraph HAL[\"Hardware Abstraction Layer\"]\n            Shared[\"HAL Shared Code\"]\n            Platforms[\"15+ Platform HALs\"]\n        end\n    end\n\n    Host -->|\"USB Serial\\n250k baud\"| Suite\n    SD -->|\"SD Interface\"| Queue\n    Suite --> Parser\n    Parser --> Suite\n    Queue --> Suite\n    Suite --> Motion\n    Suite --> Temp\n    Motion --> Planner\n    Planner --> Stepper\n    Stepper --> Motors\n    Temp --> Heaters\n    Temp --> Sensors\n    Display <-->|\"SPI/I2C/UART\"| Suite\n```\n\nThe firmware communicates with the host via serial at 250,000 baud (configurable), receiving G-code commands line-by-line. Commands are queued in a circular buffer (`GCodeQueue::ring_buffer`), parsed by `GCodeParser`, and dispatched by `GcodeSuite` to category-specific handlers (motion, temperature, configuration, calibration, etc.). The core modules handle the low-level real-time tasks: the planner generates motion blocks with jerk control and acceleration profiling, the stepper driver issues pulse trains, and the temperature manager runs PID loops on thermistor inputs.\n\n### Supported Hardware Platforms\n\n| Platform Family | MCUs | Architecture | Notes |\n| --- | --- | --- | --- |\n| STM32 (various) | STM32F0, F1, F4, F7, H7, G0 | ARM Cortex-M | Primary 32-bit target |\n| AVR | ATmega2560, ATmega1280, AT90USB | 8-bit AVR | Legacy support |\n| ESP32 | ESP32-S3, ESP32-S2 | Xtensa/RISC-V | WiFi/BLE capability |\n| SAMD | SAMD21, SAMD51 | ARM Cortex-M0+/M4 | Adafruit Feather M4 |\n| RP2040 | RP2040, RP2350 | ARM Cortex-M33 | Raspberry Pi Pico |\n| LPC | LPC1768, LPC1769 | ARM Cortex-M3 | RAMBo, Melzi boards |\n| GD32 | GD32F1, GD32F3 | ARM Cortex-M3 | GigaDevice clones |\n| HC32 | HC32F4 | ARM Cortex-M4 | JCEC chips |\n| AT32 | AT32F4 | ARM Cortex-M4 | Artery Tek |\n| Teensy | 3.1/3.2, 3.5/3.6, 4.0/4.1 | ARM Cortex-M4/M7 | PJRC boards |\n| Linux Simulator | x86/x64 | Native | CI/testing |\n| Native Simulator | Any | Native | Unit testing |\n\n## 3. Processing Pipeline\n\nThe G-code processing pipeline follows a well-defined flow from input ingestion through parsing, dispatch, and hardware actuation.\n\n```mermaid\nflowchart TD\n    InputSerial[\"Serial Input\\nUSB / UART\"] --> Queue\n    InputSD[\"SD Card\\nSdFat\"] --> Queue\n    InputProgmem[\"Program Memory\\nPROGMEM\"] --> Queue\n\n    Queue[\"GCodeQueue\\nRing Buffer\\nBUFSIZE entries\"] --> Parser\n\n    Parser[\"GCodeParser\\n• Letter/Code/Subcode\\n• Parameter extraction\\n• FASTER_GCODE_PARSER\\n  pre-scanned flags\"] --> Suite\n\n    Suite[\"GcodeSuite\\nCommand Dispatcher\\n• Subcommand routing\\n• Parameter validation\\n• Endstop events\"]\n\n    Suite --> CatMotion[\"Motion\\nG0/G1/G2/G3\"]\n    Suite --> CatTemp[\"Temperature\\nM104/M105/M106/M107/M109\"]\n    Suite --> CatConfig[\"Configuration\\nM200-M205/M301/M92\"]\n    Suite --> CatCalibrate[\"Calibration\\nG28/G33/G34/G425\"]\n    Suite --> CatSD[\"SD Card\\nM20-M34/M928\"]\n\n    CatMotion --> Planner\n    CatTemp --> Temp\n    CatCalibrate --> Motion\n\n    Planner[\"Block Planner\\n• Trapezoidal profile\\n• Jerk control\\n• Buffer: BLOCK_BUFFER_SIZE\"] --> Stepper\n    Motion[\"Motion\\n• axis_position()\\n• relative_mode\\n• dual_x_carriage\"] --> Planner\n    Temp[\"Temperature\\n• PID loops\\n• thermistor tables\\n• safety checks\"] --> Heaters\n\n    Stepper[\"Stepper Driver\\n• issue_pending()\\n• TMC SPI config\\n• Trinamic drivers\"] --> Output[\"Hardware Outputs\\n• Step/Dir pulses\\n• PWM heat/fan\\n• Serial responses\"]\n```\n\n### Key Pipeline Components\n\n**GCodeQueue** — A circular ring buffer (`RingBuffer`) that holds up to `BUFSIZE` G-code command strings. Commands enter via three injectors: serial input (USB/UART), SD card file reading, and in-firmware injected commands (PROGMEM). The queue's `advance()` method pops the next command and hands it to the parser.\n\n**GCodeParser** — Parses a single G-code line, extracting the command letter (G/M/T), code number, subcode, and all parameter values (X, Y, Z, E, F, S, P, etc.). When `FASTER_GCODE_PARSER` is enabled, the parser pre-scans all parameters into a flags array for O(1) lookups.\n\n**GcodeSuite** — The command dispatcher singleton. Each G/M code maps to a handler method within this class. Commands are routed to category subdirectories under `src/gcode/` (e.g., `motion/`, `temp/`, `config/`, `calibrate/`). The suite also handles pre- and post-command hooks for endstop events, buffer monitoring, and inactivity shutdown.\n\n## 4. Core Components\n\n### 4.1 Firmware Entry Point\n\nThe firmware lifecycle is managed by `MarlinCore.cpp` (~1,777 lines), structured around Arduino's `setup()` and `loop()` functions:\n\n- **`setup()`** — Initializes HAL pins, serial ports, all modules (stepper, temperature, motion, planner, settings), features (runout detection, power loss recovery, LEDs), and the UI subsystem. Each initialization block is wrapped in `SETUP_RUN()` for debug logging in dev mode.\n- **`loop()`** — Runs continuously (infinite loop on AVR, structured loop on 32-bit platforms). Each iteration calls `marlin.idle()`, processes the G-code queue, checks power-off timers, and handles endstop events.\n\n### 4.2 Singleton Architecture\n\nGlobal state is managed through singletons:\n\n| Singleton | File | Responsibility |\n| --- | --- | --- |\n| `marlin` | `MarlinCore.cpp/h` | Global state machine, inactivity management, kill/suicide, heatup waits |\n| `gcode` | `gcode/gcode.cpp` | G-code command dispatch |\n| `queue` | `gcode/queue.h` | Command queue ring buffer |\n| `planner` | `module/planner.cpp` | Motion block buffer and trapezoidal profiling |\n| `stepper` | `module/stepper.cpp` | Step pulse generation and TMC driver config |\n| `thermalManager` | `module/temperature.cpp` | PID loops, thermistor reading, safety monitoring |\n| `card` | `sd/cardreader.cpp` | SD card file system operations |\n| `ui` | `lcd/marlinui.cpp/h` | LCD/UI state machine and menu system |\n\n### 4.3 Module System\n\nThe `module/` directory contains the core motion and thermal management classes:\n\n| Module | File | Description |\n| --- | --- | --- |\n| **Motion** | `motion.h/cpp` | High-level axis positioning, coordinate transforms, joint interpolation |\n| **Planner** | `planner.h/cpp` | Block buffer, trapezoidal velocity profiling, junction deviation |\n| **Stepper** | `stepper.h/cpp` | Step pulse generation, direction control, TMC Trinamic SPI configuration |\n| **Temperature** | `temperature.h/cpp` | PID autotune (M303), thermistor tables, hotend/bed/heater management |\n| **Endstops** | `endstops.h/cpp` | Endstop interrupt handling, homing logic, soft endstops |\n| **Probe** | `probe.h/cpp` | Bed probing (G30, G31/G32, G38, bltouch), Z-offset management |\n| **Settings** | `settings.h/cpp` | EEPROM persistence, configuration storage and retrieval |\n| **PrintCounter** | `printcounter.h/cpp` | Print time, filament usage, and job statistics |\n| **Servo** | `servo.h/cpp` | Servo control for solenoids, lid mechanisms |\n| **Delta/Scara/Polar** | `delta.h`, `scara.h`, `polar.h` | Kinematic transforms for non-Cartesian printers |\n| **Tool Change** | `tool_change.h/cpp` | Multi-extruder tool switching, hotend offset, PTFE purge |\n\n### 4.4 Feature System\n\nThe `feature/` directory contains 80+ optional modules, each gated by a `#if ENABLED(FEATURE_NAME)` preprocessor check:\n\n**Motion Features:** Linear Advance (`linearadvance`), Pressure Advance, Adaptive Multi-Axis Stepping, Direct Stepping, Bresenham acceleration, Resonance Compensation, X-Axis Twist Correction, Z-Stepper Alignment, Backlash Compensation.\n\n**Thermal Features:** Automatic PID Tuning (M303), Thermal Protection, Probe Temperature Compensation, Mixed Extruder (`mixing`), Bowden/Direct Drive Retraction (`fwretract`).\n\n**Peripheral Features:** Power Loss Recovery (`powerloss`), Filament Runout Detection (`runout`), Ethernet Connectivity (`ethernet`), RS485 Communication (`rs485`), MMU/Multi- Material Unit (`mmu`, `mmu3`), Solenoid Control (`solenoid`), Spindle/Laser (`spindle_laser`), Case Lights (`caselight`), LED Color Control (`leds`).\n\n**UI Features:** Touch Screen (`touch`), LVGL TFT UI (`mks_ui`), DWIN Display (`dwin`), Extensible UI (`extui`), Password Protection (`password`), Joystick Input (`joystick`).\n\n**Bed Leveling:** Unified Bed Leveling (UBL), Manual Bed Leveling (MBL), Automatic Bed Leveling (ABL), G26 Mesh Validation, G35 Auto Bed Leveling, Bed Level Visualizer.\n\n## 5. G-Code Command Reference\n\nMarlin implements 100+ G-code commands organized into 14 categories under `src/gcode/`:\n\n| Category | Directory | Key Commands | Description |\n| --- | --- | --- | --- |\n| **Motion** | `motion/` | G0, G1, G2, G3, G5, G6, G80, M400, M290 | Linear/arc moves, rapid moves, dwell, wait, jog |\n| **Temperature** | `temp/` | M104/M105/M106/M107/M109, M140/M190, M303 | Hotend/bed temp set/read, fan control, PID autotune |\n| **Configuration** | `config/` | M200-M205, M301, M92, M43, M218, M217 | Extruder steps, accel/jerk, PID, hotend offset, bowden length |\n| **Calibration** | `calibrate/` | G28, G33, G34, G425, M48, M566, M665 | Home, delta calibration, nozzle purge, backlash, bellows |\n| **Geometry** | `geometry/` | G17-G19, G53-G59, G92, M206, M428 | Plane selection, coordinate systems, position reset, offsets |\n| **Control** | `control/` | M17/M18/M84, M80/M81, M3-M5, M7-M9, T | Enable axes, power, spindle, tool select, feedrate/extruder units |\n| **Probe** | `probe/` | G30, G31/G32, G38, M851, M401/M402, M102 | Bed probe, probe type, probe actions |\n| **SD Card** | `sd/` | M20-M34, M928, M1001, M1003 | File listing, select, start, stop, abort, load, save |\n| **LCD** | `lcd/` | M0, M1, M73, M117, M145, M250, M300 | Pause, progress, message, color, beep |\n| **Host** | `host/` | M16, M110, M113, M114, M115, M118, M119, M154, M360, M876 | Line numbers, machine info, endstop report, kinematic config |\n| **EEPROM** | `eeprom/` | M500, M501, M502, M503, M504 | Save/load/reset/settings EEPROM operations |\n| **Stats** | `stats/` | M31, M75-M78 | Print time, filament used, errors, buffer stats |\n| **Units** | `units/` | G20/G21, M82/M83, M149 | mm/inch, extrusion mode, temp unit display |\n| **OTA** | `ota/` | M936 | Over-the-air firmware update |\n\n## 6. Infrastructure & Deployment\n\n### 6.1 Build System\n\nMarlin uses PlatformIO as its primary build system, configured via `platformio.ini`:\n\n- **Framework**: Arduino (via PlatformIO)\n- **Build flags**: `-g3 -D__MARLIN_FIRMWARE__ -DNDEBUG -fsingle-precision-constant`\n- **Source filter**: Dynamic inclusion/exclusion of files based on target board via pre-build scripts (`configuration.py`, `common-dependencies.py`, `preflight-checks.py`)\n- **Include directory**: `Marlin/src/`\n- **Board definitions**: Custom PlatformIO board definitions in `buildroot/share/PlatformIO/boards/`\n\n### 6.2 Configuration System\n\nConfiguration is managed through a layered preprocessor conditional system:\n\n1. **`Configuration.h`** — User-editable hardware and feature configuration\n2. **`Configuration_adv.h`** — Advanced/experimental feature toggles\n3. **`Version.h`** — Build version, machine name, website URL\n4. **`inc/Conditionals-*.h`** — Auto-generated feature flags derived from Configuration.h\n5. **`inc/MarlinConfig.h`** — Prefix header including all conditionals, types, and sanity checks\n\nThe conditional system ensures that only enabled features compile, minimizing firmware footprint for resource-constrained 8-bit platforms.\n\n### 6.3 CI/CD Pipeline\n\nGitHub Actions workflows run on every pull request and push:\n\n| Workflow | Purpose |\n| --- | --- |\n| `ci-build-tests.yml` | Compiles Marlin for all supported boards (matrix strategy) |\n| `ci-unit-tests.yml` | Runs C++ unit tests on the native simulator |\n| `ci-validate-boards.yml` | Validates board pin configurations |\n| `ci-validate-pins.yml` | Checks for missing/invalid pin definitions |\n| `ci-validate-lines.yml` | Validates line count limits for 8-bit boards |\n| `auto-label.yml` | Auto-labels PRs by changed paths |\n| `check-pr.yml` | PR quality checks |\n\n### 6.4 Docker Build Environment\n\nA Dockerfile (`docker/Dockerfile`) provides a reproducible build environment:\n\n```dockerfile\nFROM python:3.11-bookworm\nRUN pip install -U platformio PyYaml\nRUN pio upgrade --dev\nWORKDIR /code\n```\n\n### 6.5 Testing\n\n- **Unit tests**: Located in `Marlin/tests/`, run via the Linux native simulator HAL\n- **Build tests**: CI compiles against 20+ board targets to catch compile errors\n- **Pin validation**: Automated checks for pin conflicts and missing definitions\n- **SdFat**: Integrated SdFat library for SD card file operations (Sd2Card, SdBaseFile, SdVolume)\n\n## 7. Extension Patterns\n\n### 7.1 Adding a New Feature\n\n1. Create your feature files in `Marlin/src/feature/` (e.g., `my_feature.h` and `my_feature.cpp`)\n2. Add `#define MY_FEATURE` to `Configuration_adv.h`\n3. The conditional system in `inc/Conditionals-*.h` will auto-generate `HAS_MY_FEATURE`\n4. Use `#if ENABLED(MY_FEATURE)` guards in your code\n5. Include your header from `MarlinCore.cpp` under the appropriate `#if ENABLED()` block\n6. Register G-code handlers in `gcode/gcode.cpp` or a new category subdirectory\n\n### 7.2 Adding a New G-Code Command\n\n1. Create a new file in the appropriate `src/gcode/<category>/` directory (e.g., `M1000.cpp`)\n2. Implement the handler method in the `GcodeSuite` class\n3. Register the command in the `process_commands()` method of `GcodeSuite`\n4. The command will be dispatched automatically when the parser encounters the letter/code\n\n### 7.3 Adding Board Support\n\n1. Create a new PlatformIO board definition in `buildroot/share/PlatformIO/boards/`\n2. Add pin definitions in `Marlin/src/pins/<family>/pins_<board>.h`\n3. If the MCU is new, add HAL support in `Marlin/src/HAL/<MCU_FAMILY>/`\n4. Update `ini/<platform>.ini` in `platformio.ini`'s `extra_configs`\n5. Run `ci-validate-pins.yml` to verify pin assignments\n\n### 7.4 Adding a Display Backend\n\n1. Create backend files in `Marlin/src/lcd/<backend>/`\n2. Implement the required display interface (SPI/I2C/UART)\n3. Add `#define ULTIPANEL` or display-specific `#define` to `Configuration.h`\n4. The LCD subsystem routes through `MarlinUI` to the appropriate backend\n\n## 8. Rules & Anti-Patterns\n\n### Best Practices\n\n- **Conditional compilation**: Always gate platform-specific code with `#if ENABLED()` or `#ifdef ARDUINO_ARCH_XXX`\n- **PROGMEM usage**: Store large strings and lookup tables in program memory on 8-bit platforms\n- **Interrupt safety**: Use `WAIT`/`NOOP` patterns for stepper ISR synchronization\n- **EEPROM limits**: Respect memory constraints — 8-bit boards have limited EEPROM (4KB-8KB)\n- **Thread safety**: The main loop and stepper ISR share state — use volatile and careful locking\n- **Static analysis**: Use `bug_on()` macros for compile-time assertion checks\n- **Code size**: 8-bit targets (AVR) have strict flash limits — enable only necessary features\n\n### Anti-Patterns\n\n- **Don't add features to `Configuration.h`** — use `Configuration_adv.h` for advanced/experimental features\n- **Don't modify HAL shared code** without understanding platform implications\n- **Don't use floating-point on AVR** without explicit `float` typing — the compiler defaults to single precision\n- **Don't block in the main loop** — all long operations must yield to `idle()` or use non-blocking patterns\n- **Don't assume 32-bit semantics** — code must compile for both 8-bit AVR and 32-bit ARM\n- **Don't hardcode pin numbers** — always use the pin definition headers\n\n## 9. Dependencies\n\n### Build Tools\n\n| Dependency       | Version           | Purpose                    |\n| ---------------- | ----------------- | -------------------------- |\n| PlatformIO       | Latest dev        | Build system and framework |\n| Arduino Core     | Platform-specific | Microcontroller SDK        |\n| GCC ARM Embedded | 12.x              | ARM cross-compiler         |\n| avr-gcc          | 7.x               | AVR cross-compiler         |\n\n### Libraries (integrated)\n\n| Library    | Purpose                                             |\n| ---------- | --------------------------------------------------- |\n| SdFat      | SD card file system (Sd2Card, SdBaseFile, SdVolume) |\n| u8glib     | OLED/LCD display driver (embedded in HAL)           |\n| LVGL       | TFT graphical UI (optional, for MKS UI)             |\n| heatshrink | G-code decompression for SD prints                  |\n\n### Platform Libraries\n\n| Platform | Libraries                     |\n| -------- | ----------------------------- |\n| STM32    | STM32 HAL/LL, STM32duino core |\n| AVR      | Arduino AVR core, TimerOne    |\n| ESP32    | ESP-IDF components, WiFi      |\n| RP2040   | Arduino RP2040 core, PIOasm   |\n| Teensy   | Teensyduino core, Bounce2     |\n| SAMD     | Arduino SAMD core             |\n\n## 10. Code Structure\n\n```\nMarlinFirmware/                  # Repo root (this directory). `cd` here for PlatformIO builds.\n├── Marlin/                      # The Arduino \"sketch\" (application source + config files)\n│   ├── Configuration.h          # User hardware configuration\n│   ├── Configuration_adv.h      # Advanced/experimental toggles\n│   ├── Marlin.ino               # Board-specific entry stub\n│   ├── Makefile                 # Alternative build (simulator)\n│   ├── Version.h                # Build version, machine name\n│   ├── config.ini               # PlatformIO extra config\n│   ├── lib/                     # Integrated libraries\n│   └── src/                     # Application source (see below)\n├── buildroot/                   # Build infrastructure\n├── ini/                         # PlatformIO platform configs\n├── docs/                        # Project documentation\n├── docker/                      # Docker build environment\n├── .github/workflows/           # CI/CD pipelines\n└── platformio.ini               # Main PlatformIO configuration\n```\n\n### Marlin/src layout\n\n```\nMarlin/src/\n├── MarlinCore.cpp/h         # Firmware entry, setup(), loop(), Marlin singleton\n├── core/                    # Core utilities (serial, language, types, mstring)\n│   ├── gcode/                   # G-code subsystem\n│   │   ├── gcode.cpp/h          # GcodeSuite dispatcher\n│   │   ├── parser.cpp/h         # GCodeParser\n│   │   ├── queue.cpp/h          # GCodeQueue ring buffer\n│   │   ├── motion/              # G0-G6, M290, M400\n│   │   ├── temp/                # M104-M109, M140-M193, M303\n│   │   ├── config/              # M200-M205, M301, M92, M218\n│   │   ├── calibrate/           # G28, G33, G34, G425, M48\n│   │   ├── bedlevel/            # G26, G35, G42, M420\n│   │   ├── geometry/            # G17-G19, G53-G59, G92\n│   │   ├── probe/               # G30-G38, M851, M401\n│   │   ├── sd/                  # M20-M34, M928\n│   │   ├── lcd/                 # M0, M1, M73, M117\n│   │   ├── host/                # M16, M110-M119\n│   │   ├── eeprom/              # M500-M504\n│   │   ├── stats/               # M31, M75-M78\n│   │   ├── units/               # G20/G21, M82/M83\n│   │   └── control/             # M3-M5, M7-M9, M17-M85, T\n│   ├── module/                  # Core modules\n│   │   ├── motion.h/cpp         # Axis positioning, kinematics\n│   │   ├── planner.h/cpp        # Block buffer, trapezoidal profiling\n│   │   ├── stepper.h/cpp        # Step pulses, TMC drivers\n│   │   ├── temperature.h/cpp    # PID, thermistors, safety\n│   │   ├── endstops.h/cpp       # Endstop interrupts, homing\n│   │   ├── probe.h/cpp          # Bed probing, Z-offset\n│   │   ├── settings.h/cpp       # EEPROM persistence\n│   │   ├── delta.h/cpp          # Delta kinematics\n│   │   ├── scara.h/cpp          # Scara kinematics\n│   │   ├── polar.h/cpp          # Polar kinematics\n│   │   ├── polargraph.h/cpp     # Polar graph kinematics\n│   │   ├── servo.h/cpp          # Servo control\n│   │   ├── printcounter.h/cpp   # Print statistics\n│   │   ├── tool_change.h/cpp    # Multi-extruder switching\n│   │   ├── ft_motion/           # Fine-tune motion\n│   │   └── stepper/             # Stepper internals, Trinamic\n│   ├── feature/                 # 80+ optional features\n│   │   ├── bedlevel/            # UBL, MBL, ABL\n│   │   ├── leds/                # LED color control\n│   │   ├── mmu/                 # Multi-material unit\n│   │   ├── mmu3/                # MMU3 variant\n│   │   ├── powerloss.h/cpp      # Power loss recovery\n│   │   ├── runout.h/cpp         # Filament runout detection\n│   │   ├── pause.h/cpp          # Pause/resume\n│   │   ├── mixing.h/cpp         # Mixed extruder\n│   │   ├── fwretract.h/cpp      # Firmware retraction\n│   │   ├── resonance/           # Resonance compensation\n│   │   ├── spindle_laser.h/cpp  # Spindle/laser control\n│   │   ├── ethernet.h/cpp       # Ethernet connectivity\n│   │   ├── solenoid.h/cpp       # Solenoid control\n│   │   ├── password/            # Password protection\n│   │   ├── joystick.h/cpp       # Joystick input\n│   │   ├── tmc_util.h/cpp       # TMC driver utilities\n│   │   └── ...                  # 60+ more features\n│   ├── lcd/                     # Display/UI subsystem\n│   │   ├── marlinui.h/cpp        # Main UI controller\n│   │   ├── HD44780/             # Hitachi HD44780 LCD\n│   │   ├── dogm/                # DOGM OLED/LCD\n│   │   ├── tft/                 # TFT displays\n│   │   ├── tft_io/              # TFT I/O drivers\n│   │   ├── dwin/                # DWIN displays\n│   │   ├── extui/               # Extensible UI (MKS LVGL)\n│   │   ├── menu/                # Menu system\n│   │   ├── touch/               # Touch screen\n│   │   ├── language/            # Multi-language strings\n│   │   └── sovol_rts/           # Sovol RTS display\n│   ├── libs/                    # Utility libraries\n│   │   ├── bresenham.h          # Bresenham line algorithm\n│   │   ├── vector_3.h/cpp       # 3D vector math\n│   │   ├── circularqueue.h      # Generic circular queue\n│   │   ├── adc/                 # ADC utilities\n│   │   ├── heatshrink/          # Decompression\n│   │   ├── nozzle.cpp/h         # Nozzle cleaning\n│   │   ├── numtostr.h/cpp       # Number-to-string\n│   │   ├── hex_print.h/cpp      # Hex printing\n│   │   ├── crc16.h/cpp          # CRC-16 calculation\n│   │   ├── stopwatch.h/cpp      # Stopwatch utility\n│   │   ├── least_squares_fit.h  # Least squares fitting\n│   │   └── ...                  # 15+ utility libs\n│   ├── sd/                      # SD card subsystem\n│   │   ├── cardreader.h/cpp     # Card reader interface\n│   │   ├── SdFat*               # SdFat library (file system)\n│   │   ├── disk_io_driver.h     # Disk I/O abstraction\n│   │   └── usb_flashdrive/      # USB flash drive support\n│   ├── pins/                    # Pin definitions (400+ files)\n│   │   ├── pins.h               # Pin inclusion router\n│   │   ├── ramps/               # Ramps board family\n│   │   ├── mega/                # Mega board family\n│   │   ├── rambo/               # Rambo board family\n│   │   ├── sanguino/            # Sanguino board family\n│   │   ├── stm32f1/             # STM32F1 boards\n│   │   ├── stm32f4/             # STM32F4 boards\n│   │   ├── stm32f7/             # STM32F7 boards\n│   │   ├── stm32h7/             # STM32H7 boards\n│   │   ├── stm32g0/             # STM32G0 boards\n│   │   ├── stm32f0/             # STM32F0 boards\n│   │   ├── sam/                 # SAM boards\n│   │   ├── samd/                # SAMD boards\n│   │   ├── rp2040/              # RP2040 boards\n│   │   ├── lpc1768/             # LPC1768 boards\n│   │   ├── lpc1769/             # LPC1769 boards\n│   │   ├── teensy2/             # Teensy 2.x boards\n│   │   ├── teensy3/             # Teensy 3.x boards\n│   │   ├── teensy4/             # Teensy 4.x boards\n│   │   ├── esp32/               # ESP32 boards\n│   │   ├── gd32f1/              # GD32F1 boards\n│   │   ├── gd32f3/              # GD32F3 boards\n│   │   ├── hc32f4/              # HC32F4 boards\n│   │   ├── at32f4/              # AT32F4 boards\n│   │   └── native/              # Native/simulator\n│   ├── HAL/                     # Hardware Abstraction Layer\n│   │   ├── HAL.h                # HAL interface definition\n│   │   ├── platforms.h          # Platform selection\n│   │   ├── shared/              # Cross-platform HAL code\n│   │   │   ├── HAL.cpp/h        # Shared HAL implementation\n│   │   │   ├── Delay.h          # Safe delay function\n│   │   │   ├── eeprom_api.h     # EEPROM API\n│   │   │   ├── cpu_exception/   # Exception handling\n│   │   │   └── backtrace/       # Stack backtrace\n│   │   ├── STM32/               # STM32 platform HAL\n│   │   ├── AVR/                 # AVR platform HAL\n│   │   ├── ESP32/               # ESP32 platform HAL\n│   │   ├── DUE/                 # Arduino Due HAL\n│   │   ├── SAMD21/              # SAMD21 HAL\n│   │   ├── SAMD51/              # SAMD51 HAL\n│   │   ├── RP2040/              # RP2040 HAL\n│   │   ├── LPC1768/             # LPC1768 HAL\n│   │   ├── GD32_MFL/            # GD32 HAL\n│   │   ├── HC32/                # HC32 HAL\n│   │   ├── AT32/                # AT32 HAL\n│   │   ├── TEENSY31_32/         # Teensy 3.1/3.2 HAL\n│   │   ├── TEENSY35_36/         # Teensy 3.5/3.6 HAL\n│   │   ├── TEENSY40_41/         # Teensy 4.0/4.1 HAL\n│   │   ├── STM32F1/             # STM32F1 HAL\n│   │   ├── LINUX/               # Linux simulator HAL\n│   │   └── NATIVE_SIM/          # Native simulator HAL\n│   └── tests/                   # Unit tests\n│       ├── unit_tests.h/cpp     # Test suite\n│       └── *.ini                # Test configurations\n├── docs/                        # Project documentation\n│   ├── AGENTS.md                # This document\n│   └── diagrams/                # Architecture diagrams\n│       ├── high-level-architecture.drawio\n│       ├── processing-pipeline.drawio\n│       └── component-relationships.drawio\n├── buildroot/                   # Build infrastructure\n│   ├── share/PlatformIO/        # PlatformIO board definitions & scripts\n│   ├── test-gcode/              # G-code test files\n│   └── tests/                   # Build test configurations\n├── ini/                         # PlatformIO platform configs\n│   ├── avr.ini, due.ini, esp32.ini\n│   ├── stm32-common.ini, stm32f1.ini, stm32f4.ini\n│   ├── stm32f7.ini, stm32h7.ini, stm32g0.ini\n│   ├── samd21.ini, samd51.ini\n│   ├── raspberrypi.ini, teensy.ini\n│   ├── at32.ini, gd32.ini, hc32.ini\n│   ├── lpc176x.ini, native.ini\n│   ├── features.ini, renamed.ini\n│   └── stm32f1-maple.ini\n├── test/                        # Root-level test configurations\n├── docker/                      # Docker build environment\n├── .github/workflows/           # CI/CD pipelines\n└── platformio.ini               # Main PlatformIO configuration\n```\n\n---\n\n_This document was consolidated from `docs/project-summary.md` into the top-level `AGENTS.md` on 2026-07-11 to serve as the canonical repo orientation reference. It reflects the codebase as of the bugfix-2.1.x branch._\n"},"items":[{"name":"AGENTS.md","path":"AGENTS.md","title":"AGENTS.md","content":"# Marlin 3D Printer Firmware\n\n> This file consolidates the project summary (`docs/project-summary.md`) into the top-level agent reference. It is the canonical orientation document for the whole repo. Per-HAL working notes live in `Marlin/src/HAL/<FAMILY>/AGENTS.md` (e.g. `Marlin/src/HAL/AT32/AGENTS.md`).\n\n## 1. Executive Summary\n\nMarlin is an open-source firmware for 3D printers, written in C/C++ and built on the Arduino framework via PlatformIO. It sits between a host computer (running slicer software) and the printer's hardware, translating G-code movement commands into precise stepper motor control, temperature regulation, and peripheral management. The firmware supports 15+ microcontroller platforms (STM32, AVR, ESP32, RP2040, and more), 400+ pin configuration files across 24 board families, and a modular feature system with 80+ enable/disable features. At over 2,500 source files, Marlin is one of the most widely deployed 3D printer firmware projects in the world, licensed under GPL v3.0.\n\n## 2. Architecture Overview\n\nMarlin follows a layered embedded firmware architecture organized around a Hardware Abstraction Layer (HAL), a G-code command processing pipeline, a set of core motion/thermal modules, and a rich feature system. The firmware's singleton entry point is the `Marlin` class (`MarlinCore`), which manages global state and the main control loop.\n\n```mermaid\ngraph TB\n    subgraph Environment[\"Printer Environment\"]\n        Host[\"Host Computer\\n(Slicer / Host Software)\"]\n        SD[\"SD Card\\n(SdFat)\"]\n        Sensors[\"Thermistors &\\nEndstops\"]\n        Motors[\"Stepper Motors\\n&amp; Drivers\"]\n        Heaters[\"Heaters &amp; Fans\"]\n        Display[\"LCD / TFT / DWIN\"]\n    end\n\n    subgraph Marlin[\"Marlin Firmware\"]\n        subgraph GCode[\"G-Code Subsystem\"]\n            Queue[\"GCodeQueue\\nRing Buffer\"]\n            Parser[\"GCodeParser\\nParameter Extraction\"]\n            Suite[\"GcodeSuite\\nCommand Dispatcher\"]\n        end\n        subgraph Modules[\"Core Modules\"]\n            Motion[\"Motion Planner\"]\n            Planner[\"Block Planner\"]\n            Stepper[\"Stepper Driver\"]\n            Temp[\"Temperature Manager\"]\n        end\n        subgraph Features[\"Feature System\\n80+ modules\"]\n            BedLevel[\"Bed Leveling\"]\n            PowerLoss[\"Power Loss Recovery\"]\n            Runout[\"Filament Runout\"]\n            MMU[\"Multi-Material\\nUnit\"]\n        end\n        subgraph HAL[\"Hardware Abstraction Layer\"]\n            Shared[\"HAL Shared Code\"]\n            Platforms[\"15+ Platform HALs\"]\n        end\n    end\n\n    Host -->|\"USB Serial\\n250k baud\"| Suite\n    SD -->|\"SD Interface\"| Queue\n    Suite --> Parser\n    Parser --> Suite\n    Queue --> Suite\n    Suite --> Motion\n    Suite --> Temp\n    Motion --> Planner\n    Planner --> Stepper\n    Stepper --> Motors\n    Temp --> Heaters\n    Temp --> Sensors\n    Display <-->|\"SPI/I2C/UART\"| Suite\n```\n\nThe firmware communicates with the host via serial at 250,000 baud (configurable), receiving G-code commands line-by-line. Commands are queued in a circular buffer (`GCodeQueue::ring_buffer`), parsed by `GCodeParser`, and dispatched by `GcodeSuite` to category-specific handlers (motion, temperature, configuration, calibration, etc.). The core modules handle the low-level real-time tasks: the planner generates motion blocks with jerk control and acceleration profiling, the stepper driver issues pulse trains, and the temperature manager runs PID loops on thermistor inputs.\n\n### Supported Hardware Platforms\n\n| Platform Family | MCUs | Architecture | Notes |\n| --- | --- | --- | --- |\n| STM32 (various) | STM32F0, F1, F4, F7, H7, G0 | ARM Cortex-M | Primary 32-bit target |\n| AVR | ATmega2560, ATmega1280, AT90USB | 8-bit AVR | Legacy support |\n| ESP32 | ESP32-S3, ESP32-S2 | Xtensa/RISC-V | WiFi/BLE capability |\n| SAMD | SAMD21, SAMD51 | ARM Cortex-M0+/M4 | Adafruit Feather M4 |\n| RP2040 | RP2040, RP2350 | ARM Cortex-M33 | Raspberry Pi Pico |\n| LPC | LPC1768, LPC1769 | ARM Cortex-M3 | RAMBo, Melzi boards |\n| GD32 | GD32F1, GD32F3 | ARM Cortex-M3 | GigaDevice clones |\n| HC32 | HC32F4 | ARM Cortex-M4 | JCEC chips |\n| AT32 | AT32F4 | ARM Cortex-M4 | Artery Tek |\n| Teensy | 3.1/3.2, 3.5/3.6, 4.0/4.1 | ARM Cortex-M4/M7 | PJRC boards |\n| Linux Simulator | x86/x64 | Native | CI/testing |\n| Native Simulator | Any | Native | Unit testing |\n\n## 3. Processing Pipeline\n\nThe G-code processing pipeline follows a well-defined flow from input ingestion through parsing, dispatch, and hardware actuation.\n\n```mermaid\nflowchart TD\n    InputSerial[\"Serial Input\\nUSB / UART\"] --> Queue\n    InputSD[\"SD Card\\nSdFat\"] --> Queue\n    InputProgmem[\"Program Memory\\nPROGMEM\"] --> Queue\n\n    Queue[\"GCodeQueue\\nRing Buffer\\nBUFSIZE entries\"] --> Parser\n\n    Parser[\"GCodeParser\\n• Letter/Code/Subcode\\n• Parameter extraction\\n• FASTER_GCODE_PARSER\\n  pre-scanned flags\"] --> Suite\n\n    Suite[\"GcodeSuite\\nCommand Dispatcher\\n• Subcommand routing\\n• Parameter validation\\n• Endstop events\"]\n\n    Suite --> CatMotion[\"Motion\\nG0/G1/G2/G3\"]\n    Suite --> CatTemp[\"Temperature\\nM104/M105/M106/M107/M109\"]\n    Suite --> CatConfig[\"Configuration\\nM200-M205/M301/M92\"]\n    Suite --> CatCalibrate[\"Calibration\\nG28/G33/G34/G425\"]\n    Suite --> CatSD[\"SD Card\\nM20-M34/M928\"]\n\n    CatMotion --> Planner\n    CatTemp --> Temp\n    CatCalibrate --> Motion\n\n    Planner[\"Block Planner\\n• Trapezoidal profile\\n• Jerk control\\n• Buffer: BLOCK_BUFFER_SIZE\"] --> Stepper\n    Motion[\"Motion\\n• axis_position()\\n• relative_mode\\n• dual_x_carriage\"] --> Planner\n    Temp[\"Temperature\\n• PID loops\\n• thermistor tables\\n• safety checks\"] --> Heaters\n\n    Stepper[\"Stepper Driver\\n• issue_pending()\\n• TMC SPI config\\n• Trinamic drivers\"] --> Output[\"Hardware Outputs\\n• Step/Dir pulses\\n• PWM heat/fan\\n• Serial responses\"]\n```\n\n### Key Pipeline Components\n\n**GCodeQueue** — A circular ring buffer (`RingBuffer`) that holds up to `BUFSIZE` G-code command strings. Commands enter via three injectors: serial input (USB/UART), SD card file reading, and in-firmware injected commands (PROGMEM). The queue's `advance()` method pops the next command and hands it to the parser.\n\n**GCodeParser** — Parses a single G-code line, extracting the command letter (G/M/T), code number, subcode, and all parameter values (X, Y, Z, E, F, S, P, etc.). When `FASTER_GCODE_PARSER` is enabled, the parser pre-scans all parameters into a flags array for O(1) lookups.\n\n**GcodeSuite** — The command dispatcher singleton. Each G/M code maps to a handler method within this class. Commands are routed to category subdirectories under `src/gcode/` (e.g., `motion/`, `temp/`, `config/`, `calibrate/`). The suite also handles pre- and post-command hooks for endstop events, buffer monitoring, and inactivity shutdown.\n\n## 4. Core Components\n\n### 4.1 Firmware Entry Point\n\nThe firmware lifecycle is managed by `MarlinCore.cpp` (~1,777 lines), structured around Arduino's `setup()` and `loop()` functions:\n\n- **`setup()`** — Initializes HAL pins, serial ports, all modules (stepper, temperature, motion, planner, settings), features (runout detection, power loss recovery, LEDs), and the UI subsystem. Each initialization block is wrapped in `SETUP_RUN()` for debug logging in dev mode.\n- **`loop()`** — Runs continuously (infinite loop on AVR, structured loop on 32-bit platforms). Each iteration calls `marlin.idle()`, processes the G-code queue, checks power-off timers, and handles endstop events.\n\n### 4.2 Singleton Architecture\n\nGlobal state is managed through singletons:\n\n| Singleton | File | Responsibility |\n| --- | --- | --- |\n| `marlin` | `MarlinCore.cpp/h` | Global state machine, inactivity management, kill/suicide, heatup waits |\n| `gcode` | `gcode/gcode.cpp` | G-code command dispatch |\n| `queue` | `gcode/queue.h` | Command queue ring buffer |\n| `planner` | `module/planner.cpp` | Motion block buffer and trapezoidal profiling |\n| `stepper` | `module/stepper.cpp` | Step pulse generation and TMC driver config |\n| `thermalManager` | `module/temperature.cpp` | PID loops, thermistor reading, safety monitoring |\n| `card` | `sd/cardreader.cpp` | SD card file system operations |\n| `ui` | `lcd/marlinui.cpp/h` | LCD/UI state machine and menu system |\n\n### 4.3 Module System\n\nThe `module/` directory contains the core motion and thermal management classes:\n\n| Module | File | Description |\n| --- | --- | --- |\n| **Motion** | `motion.h/cpp` | High-level axis positioning, coordinate transforms, joint interpolation |\n| **Planner** | `planner.h/cpp` | Block buffer, trapezoidal velocity profiling, junction deviation |\n| **Stepper** | `stepper.h/cpp` | Step pulse generation, direction control, TMC Trinamic SPI configuration |\n| **Temperature** | `temperature.h/cpp` | PID autotune (M303), thermistor tables, hotend/bed/heater management |\n| **Endstops** | `endstops.h/cpp` | Endstop interrupt handling, homing logic, soft endstops |\n| **Probe** | `probe.h/cpp` | Bed probing (G30, G31/G32, G38, bltouch), Z-offset management |\n| **Settings** | `settings.h/cpp` | EEPROM persistence, configuration storage and retrieval |\n| **PrintCounter** | `printcounter.h/cpp` | Print time, filament usage, and job statistics |\n| **Servo** | `servo.h/cpp` | Servo control for solenoids, lid mechanisms |\n| **Delta/Scara/Polar** | `delta.h`, `scara.h`, `polar.h` | Kinematic transforms for non-Cartesian printers |\n| **Tool Change** | `tool_change.h/cpp` | Multi-extruder tool switching, hotend offset, PTFE purge |\n\n### 4.4 Feature System\n\nThe `feature/` directory contains 80+ optional modules, each gated by a `#if ENABLED(FEATURE_NAME)` preprocessor check:\n\n**Motion Features:** Linear Advance (`linearadvance`), Pressure Advance, Adaptive Multi-Axis Stepping, Direct Stepping, Bresenham acceleration, Resonance Compensation, X-Axis Twist Correction, Z-Stepper Alignment, Backlash Compensation.\n\n**Thermal Features:** Automatic PID Tuning (M303), Thermal Protection, Probe Temperature Compensation, Mixed Extruder (`mixing`), Bowden/Direct Drive Retraction (`fwretract`).\n\n**Peripheral Features:** Power Loss Recovery (`powerloss`), Filament Runout Detection (`runout`), Ethernet Connectivity (`ethernet`), RS485 Communication (`rs485`), MMU/Multi- Material Unit (`mmu`, `mmu3`), Solenoid Control (`solenoid`), Spindle/Laser (`spindle_laser`), Case Lights (`caselight`), LED Color Control (`leds`).\n\n**UI Features:** Touch Screen (`touch`), LVGL TFT UI (`mks_ui`), DWIN Display (`dwin`), Extensible UI (`extui`), Password Protection (`password`), Joystick Input (`joystick`).\n\n**Bed Leveling:** Unified Bed Leveling (UBL), Manual Bed Leveling (MBL), Automatic Bed Leveling (ABL), G26 Mesh Validation, G35 Auto Bed Leveling, Bed Level Visualizer.\n\n## 5. G-Code Command Reference\n\nMarlin implements 100+ G-code commands organized into 14 categories under `src/gcode/`:\n\n| Category | Directory | Key Commands | Description |\n| --- | --- | --- | --- |\n| **Motion** | `motion/` | G0, G1, G2, G3, G5, G6, G80, M400, M290 | Linear/arc moves, rapid moves, dwell, wait, jog |\n| **Temperature** | `temp/` | M104/M105/M106/M107/M109, M140/M190, M303 | Hotend/bed temp set/read, fan control, PID autotune |\n| **Configuration** | `config/` | M200-M205, M301, M92, M43, M218, M217 | Extruder steps, accel/jerk, PID, hotend offset, bowden length |\n| **Calibration** | `calibrate/` | G28, G33, G34, G425, M48, M566, M665 | Home, delta calibration, nozzle purge, backlash, bellows |\n| **Geometry** | `geometry/` | G17-G19, G53-G59, G92, M206, M428 | Plane selection, coordinate systems, position reset, offsets |\n| **Control** | `control/` | M17/M18/M84, M80/M81, M3-M5, M7-M9, T | Enable axes, power, spindle, tool select, feedrate/extruder units |\n| **Probe** | `probe/` | G30, G31/G32, G38, M851, M401/M402, M102 | Bed probe, probe type, probe actions |\n| **SD Card** | `sd/` | M20-M34, M928, M1001, M1003 | File listing, select, start, stop, abort, load, save |\n| **LCD** | `lcd/` | M0, M1, M73, M117, M145, M250, M300 | Pause, progress, message, color, beep |\n| **Host** | `host/` | M16, M110, M113, M114, M115, M118, M119, M154, M360, M876 | Line numbers, machine info, endstop report, kinematic config |\n| **EEPROM** | `eeprom/` | M500, M501, M502, M503, M504 | Save/load/reset/settings EEPROM operations |\n| **Stats** | `stats/` | M31, M75-M78 | Print time, filament used, errors, buffer stats |\n| **Units** | `units/` | G20/G21, M82/M83, M149 | mm/inch, extrusion mode, temp unit display |\n| **OTA** | `ota/` | M936 | Over-the-air firmware update |\n\n## 6. Infrastructure & Deployment\n\n### 6.1 Build System\n\nMarlin uses PlatformIO as its primary build system, configured via `platformio.ini`:\n\n- **Framework**: Arduino (via PlatformIO)\n- **Build flags**: `-g3 -D__MARLIN_FIRMWARE__ -DNDEBUG -fsingle-precision-constant`\n- **Source filter**: Dynamic inclusion/exclusion of files based on target board via pre-build scripts (`configuration.py`, `common-dependencies.py`, `preflight-checks.py`)\n- **Include directory**: `Marlin/src/`\n- **Board definitions**: Custom PlatformIO board definitions in `buildroot/share/PlatformIO/boards/`\n\n### 6.2 Configuration System\n\nConfiguration is managed through a layered preprocessor conditional system:\n\n1. **`Configuration.h`** — User-editable hardware and feature configuration\n2. **`Configuration_adv.h`** — Advanced/experimental feature toggles\n3. **`Version.h`** — Build version, machine name, website URL\n4. **`inc/Conditionals-*.h`** — Auto-generated feature flags derived from Configuration.h\n5. **`inc/MarlinConfig.h`** — Prefix header including all conditionals, types, and sanity checks\n\nThe conditional system ensures that only enabled features compile, minimizing firmware footprint for resource-constrained 8-bit platforms.\n\n### 6.3 CI/CD Pipeline\n\nGitHub Actions workflows run on every pull request and push:\n\n| Workflow | Purpose |\n| --- | --- |\n| `ci-build-tests.yml` | Compiles Marlin for all supported boards (matrix strategy) |\n| `ci-unit-tests.yml` | Runs C++ unit tests on the native simulator |\n| `ci-validate-boards.yml` | Validates board pin configurations |\n| `ci-validate-pins.yml` | Checks for missing/invalid pin definitions |\n| `ci-validate-lines.yml` | Validates line count limits for 8-bit boards |\n| `auto-label.yml` | Auto-labels PRs by changed paths |\n| `check-pr.yml` | PR quality checks |\n\n### 6.4 Docker Build Environment\n\nA Dockerfile (`docker/Dockerfile`) provides a reproducible build environment:\n\n```dockerfile\nFROM python:3.11-bookworm\nRUN pip install -U platformio PyYaml\nRUN pio upgrade --dev\nWORKDIR /code\n```\n\n### 6.5 Testing\n\n- **Unit tests**: Located in `Marlin/tests/`, run via the Linux native simulator HAL\n- **Build tests**: CI compiles against 20+ board targets to catch compile errors\n- **Pin validation**: Automated checks for pin conflicts and missing definitions\n- **SdFat**: Integrated SdFat library for SD card file operations (Sd2Card, SdBaseFile, SdVolume)\n\n## 7. Extension Patterns\n\n### 7.1 Adding a New Feature\n\n1. Create your feature files in `Marlin/src/feature/` (e.g., `my_feature.h` and `my_feature.cpp`)\n2. Add `#define MY_FEATURE` to `Configuration_adv.h`\n3. The conditional system in `inc/Conditionals-*.h` will auto-generate `HAS_MY_FEATURE`\n4. Use `#if ENABLED(MY_FEATURE)` guards in your code\n5. Include your header from `MarlinCore.cpp` under the appropriate `#if ENABLED()` block\n6. Register G-code handlers in `gcode/gcode.cpp` or a new category subdirectory\n\n### 7.2 Adding a New G-Code Command\n\n1. Create a new file in the appropriate `src/gcode/<category>/` directory (e.g., `M1000.cpp`)\n2. Implement the handler method in the `GcodeSuite` class\n3. Register the command in the `process_commands()` method of `GcodeSuite`\n4. The command will be dispatched automatically when the parser encounters the letter/code\n\n### 7.3 Adding Board Support\n\n1. Create a new PlatformIO board definition in `buildroot/share/PlatformIO/boards/`\n2. Add pin definitions in `Marlin/src/pins/<family>/pins_<board>.h`\n3. If the MCU is new, add HAL support in `Marlin/src/HAL/<MCU_FAMILY>/`\n4. Update `ini/<platform>.ini` in `platformio.ini`'s `extra_configs`\n5. Run `ci-validate-pins.yml` to verify pin assignments\n\n### 7.4 Adding a Display Backend\n\n1. Create backend files in `Marlin/src/lcd/<backend>/`\n2. Implement the required display interface (SPI/I2C/UART)\n3. Add `#define ULTIPANEL` or display-specific `#define` to `Configuration.h`\n4. The LCD subsystem routes through `MarlinUI` to the appropriate backend\n\n## 8. Rules & Anti-Patterns\n\n### Best Practices\n\n- **Conditional compilation**: Always gate platform-specific code with `#if ENABLED()` or `#ifdef ARDUINO_ARCH_XXX`\n- **PROGMEM usage**: Store large strings and lookup tables in program memory on 8-bit platforms\n- **Interrupt safety**: Use `WAIT`/`NOOP` patterns for stepper ISR synchronization\n- **EEPROM limits**: Respect memory constraints — 8-bit boards have limited EEPROM (4KB-8KB)\n- **Thread safety**: The main loop and stepper ISR share state — use volatile and careful locking\n- **Static analysis**: Use `bug_on()` macros for compile-time assertion checks\n- **Code size**: 8-bit targets (AVR) have strict flash limits — enable only necessary features\n\n### Anti-Patterns\n\n- **Don't add features to `Configuration.h`** — use `Configuration_adv.h` for advanced/experimental features\n- **Don't modify HAL shared code** without understanding platform implications\n- **Don't use floating-point on AVR** without explicit `float` typing — the compiler defaults to single precision\n- **Don't block in the main loop** — all long operations must yield to `idle()` or use non-blocking patterns\n- **Don't assume 32-bit semantics** — code must compile for both 8-bit AVR and 32-bit ARM\n- **Don't hardcode pin numbers** — always use the pin definition headers\n\n## 9. Dependencies\n\n### Build Tools\n\n| Dependency       | Version           | Purpose                    |\n| ---------------- | ----------------- | -------------------------- |\n| PlatformIO       | Latest dev        | Build system and framework |\n| Arduino Core     | Platform-specific | Microcontroller SDK        |\n| GCC ARM Embedded | 12.x              | ARM cross-compiler         |\n| avr-gcc          | 7.x               | AVR cross-compiler         |\n\n### Libraries (integrated)\n\n| Library    | Purpose                                             |\n| ---------- | --------------------------------------------------- |\n| SdFat      | SD card file system (Sd2Card, SdBaseFile, SdVolume) |\n| u8glib     | OLED/LCD display driver (embedded in HAL)           |\n| LVGL       | TFT graphical UI (optional, for MKS UI)             |\n| heatshrink | G-code decompression for SD prints                  |\n\n### Platform Libraries\n\n| Platform | Libraries                     |\n| -------- | ----------------------------- |\n| STM32    | STM32 HAL/LL, STM32duino core |\n| AVR      | Arduino AVR core, TimerOne    |\n| ESP32    | ESP-IDF components, WiFi      |\n| RP2040   | Arduino RP2040 core, PIOasm   |\n| Teensy   | Teensyduino core, Bounce2     |\n| SAMD     | Arduino SAMD core             |\n\n## 10. Code Structure\n\n```\nMarlinFirmware/                  # Repo root (this directory). `cd` here for PlatformIO builds.\n├── Marlin/                      # The Arduino \"sketch\" (application source + config files)\n│   ├── Configuration.h          # User hardware configuration\n│   ├── Configuration_adv.h      # Advanced/experimental toggles\n│   ├── Marlin.ino               # Board-specific entry stub\n│   ├── Makefile                 # Alternative build (simulator)\n│   ├── Version.h                # Build version, machine name\n│   ├── config.ini               # PlatformIO extra config\n│   ├── lib/                     # Integrated libraries\n│   └── src/                     # Application source (see below)\n├── buildroot/                   # Build infrastructure\n├── ini/                         # PlatformIO platform configs\n├── docs/                        # Project documentation\n├── docker/                      # Docker build environment\n├── .github/workflows/           # CI/CD pipelines\n└── platformio.ini               # Main PlatformIO configuration\n```\n\n### Marlin/src layout\n\n```\nMarlin/src/\n├── MarlinCore.cpp/h         # Firmware entry, setup(), loop(), Marlin singleton\n├── core/                    # Core utilities (serial, language, types, mstring)\n│   ├── gcode/                   # G-code subsystem\n│   │   ├── gcode.cpp/h          # GcodeSuite dispatcher\n│   │   ├── parser.cpp/h         # GCodeParser\n│   │   ├── queue.cpp/h          # GCodeQueue ring buffer\n│   │   ├── motion/              # G0-G6, M290, M400\n│   │   ├── temp/                # M104-M109, M140-M193, M303\n│   │   ├── config/              # M200-M205, M301, M92, M218\n│   │   ├── calibrate/           # G28, G33, G34, G425, M48\n│   │   ├── bedlevel/            # G26, G35, G42, M420\n│   │   ├── geometry/            # G17-G19, G53-G59, G92\n│   │   ├── probe/               # G30-G38, M851, M401\n│   │   ├── sd/                  # M20-M34, M928\n│   │   ├── lcd/                 # M0, M1, M73, M117\n│   │   ├── host/                # M16, M110-M119\n│   │   ├── eeprom/              # M500-M504\n│   │   ├── stats/               # M31, M75-M78\n│   │   ├── units/               # G20/G21, M82/M83\n│   │   └── control/             # M3-M5, M7-M9, M17-M85, T\n│   ├── module/                  # Core modules\n│   │   ├── motion.h/cpp         # Axis positioning, kinematics\n│   │   ├── planner.h/cpp        # Block buffer, trapezoidal profiling\n│   │   ├── stepper.h/cpp        # Step pulses, TMC drivers\n│   │   ├── temperature.h/cpp    # PID, thermistors, safety\n│   │   ├── endstops.h/cpp       # Endstop interrupts, homing\n│   │   ├── probe.h/cpp          # Bed probing, Z-offset\n│   │   ├── settings.h/cpp       # EEPROM persistence\n│   │   ├── delta.h/cpp          # Delta kinematics\n│   │   ├── scara.h/cpp          # Scara kinematics\n│   │   ├── polar.h/cpp          # Polar kinematics\n│   │   ├── polargraph.h/cpp     # Polar graph kinematics\n│   │   ├── servo.h/cpp          # Servo control\n│   │   ├── printcounter.h/cpp   # Print statistics\n│   │   ├── tool_change.h/cpp    # Multi-extruder switching\n│   │   ├── ft_motion/           # Fine-tune motion\n│   │   └── stepper/             # Stepper internals, Trinamic\n│   ├── feature/                 # 80+ optional features\n│   │   ├── bedlevel/            # UBL, MBL, ABL\n│   │   ├── leds/                # LED color control\n│   │   ├── mmu/                 # Multi-material unit\n│   │   ├── mmu3/                # MMU3 variant\n│   │   ├── powerloss.h/cpp      # Power loss recovery\n│   │   ├── runout.h/cpp         # Filament runout detection\n│   │   ├── pause.h/cpp          # Pause/resume\n│   │   ├── mixing.h/cpp         # Mixed extruder\n│   │   ├── fwretract.h/cpp      # Firmware retraction\n│   │   ├── resonance/           # Resonance compensation\n│   │   ├── spindle_laser.h/cpp  # Spindle/laser control\n│   │   ├── ethernet.h/cpp       # Ethernet connectivity\n│   │   ├── solenoid.h/cpp       # Solenoid control\n│   │   ├── password/            # Password protection\n│   │   ├── joystick.h/cpp       # Joystick input\n│   │   ├── tmc_util.h/cpp       # TMC driver utilities\n│   │   └── ...                  # 60+ more features\n│   ├── lcd/                     # Display/UI subsystem\n│   │   ├── marlinui.h/cpp        # Main UI controller\n│   │   ├── HD44780/             # Hitachi HD44780 LCD\n│   │   ├── dogm/                # DOGM OLED/LCD\n│   │   ├── tft/                 # TFT displays\n│   │   ├── tft_io/              # TFT I/O drivers\n│   │   ├── dwin/                # DWIN displays\n│   │   ├── extui/               # Extensible UI (MKS LVGL)\n│   │   ├── menu/                # Menu system\n│   │   ├── touch/               # Touch screen\n│   │   ├── language/            # Multi-language strings\n│   │   └── sovol_rts/           # Sovol RTS display\n│   ├── libs/                    # Utility libraries\n│   │   ├── bresenham.h          # Bresenham line algorithm\n│   │   ├── vector_3.h/cpp       # 3D vector math\n│   │   ├── circularqueue.h      # Generic circular queue\n│   │   ├── adc/                 # ADC utilities\n│   │   ├── heatshrink/          # Decompression\n│   │   ├── nozzle.cpp/h         # Nozzle cleaning\n│   │   ├── numtostr.h/cpp       # Number-to-string\n│   │   ├── hex_print.h/cpp      # Hex printing\n│   │   ├── crc16.h/cpp          # CRC-16 calculation\n│   │   ├── stopwatch.h/cpp      # Stopwatch utility\n│   │   ├── least_squares_fit.h  # Least squares fitting\n│   │   └── ...                  # 15+ utility libs\n│   ├── sd/                      # SD card subsystem\n│   │   ├── cardreader.h/cpp     # Card reader interface\n│   │   ├── SdFat*               # SdFat library (file system)\n│   │   ├── disk_io_driver.h     # Disk I/O abstraction\n│   │   └── usb_flashdrive/      # USB flash drive support\n│   ├── pins/                    # Pin definitions (400+ files)\n│   │   ├── pins.h               # Pin inclusion router\n│   │   ├── ramps/               # Ramps board family\n│   │   ├── mega/                # Mega board family\n│   │   ├── rambo/               # Rambo board family\n│   │   ├── sanguino/            # Sanguino board family\n│   │   ├── stm32f1/             # STM32F1 boards\n│   │   ├── stm32f4/             # STM32F4 boards\n│   │   ├── stm32f7/             # STM32F7 boards\n│   │   ├── stm32h7/             # STM32H7 boards\n│   │   ├── stm32g0/             # STM32G0 boards\n│   │   ├── stm32f0/             # STM32F0 boards\n│   │   ├── sam/                 # SAM boards\n│   │   ├── samd/                # SAMD boards\n│   │   ├── rp2040/              # RP2040 boards\n│   │   ├── lpc1768/             # LPC1768 boards\n│   │   ├── lpc1769/             # LPC1769 boards\n│   │   ├── teensy2/             # Teensy 2.x boards\n│   │   ├── teensy3/             # Teensy 3.x boards\n│   │   ├── teensy4/             # Teensy 4.x boards\n│   │   ├── esp32/               # ESP32 boards\n│   │   ├── gd32f1/              # GD32F1 boards\n│   │   ├── gd32f3/              # GD32F3 boards\n│   │   ├── hc32f4/              # HC32F4 boards\n│   │   ├── at32f4/              # AT32F4 boards\n│   │   └── native/              # Native/simulator\n│   ├── HAL/                     # Hardware Abstraction Layer\n│   │   ├── HAL.h                # HAL interface definition\n│   │   ├── platforms.h          # Platform selection\n│   │   ├── shared/              # Cross-platform HAL code\n│   │   │   ├── HAL.cpp/h        # Shared HAL implementation\n│   │   │   ├── Delay.h          # Safe delay function\n│   │   │   ├── eeprom_api.h     # EEPROM API\n│   │   │   ├── cpu_exception/   # Exception handling\n│   │   │   └── backtrace/       # Stack backtrace\n│   │   ├── STM32/               # STM32 platform HAL\n│   │   ├── AVR/                 # AVR platform HAL\n│   │   ├── ESP32/               # ESP32 platform HAL\n│   │   ├── DUE/                 # Arduino Due HAL\n│   │   ├── SAMD21/              # SAMD21 HAL\n│   │   ├── SAMD51/              # SAMD51 HAL\n│   │   ├── RP2040/              # RP2040 HAL\n│   │   ├── LPC1768/             # LPC1768 HAL\n│   │   ├── GD32_MFL/            # GD32 HAL\n│   │   ├── HC32/                # HC32 HAL\n│   │   ├── AT32/                # AT32 HAL\n│   │   ├── TEENSY31_32/         # Teensy 3.1/3.2 HAL\n│   │   ├── TEENSY35_36/         # Teensy 3.5/3.6 HAL\n│   │   ├── TEENSY40_41/         # Teensy 4.0/4.1 HAL\n│   │   ├── STM32F1/             # STM32F1 HAL\n│   │   ├── LINUX/               # Linux simulator HAL\n│   │   └── NATIVE_SIM/          # Native simulator HAL\n│   └── tests/                   # Unit tests\n│       ├── unit_tests.h/cpp     # Test suite\n│       └── *.ini                # Test configurations\n├── docs/                        # Project documentation\n│   ├── AGENTS.md                # This document\n│   └── diagrams/                # Architecture diagrams\n│       ├── high-level-architecture.drawio\n│       ├── processing-pipeline.drawio\n│       └── component-relationships.drawio\n├── buildroot/                   # Build infrastructure\n│   ├── share/PlatformIO/        # PlatformIO board definitions & scripts\n│   ├── test-gcode/              # G-code test files\n│   └── tests/                   # Build test configurations\n├── ini/                         # PlatformIO platform configs\n│   ├── avr.ini, due.ini, esp32.ini\n│   ├── stm32-common.ini, stm32f1.ini, stm32f4.ini\n│   ├── stm32f7.ini, stm32h7.ini, stm32g0.ini\n│   ├── samd21.ini, samd51.ini\n│   ├── raspberrypi.ini, teensy.ini\n│   ├── at32.ini, gd32.ini, hc32.ini\n│   ├── lpc176x.ini, native.ini\n│   ├── features.ini, renamed.ini\n│   └── stm32f1-maple.ini\n├── test/                        # Root-level test configurations\n├── docker/                      # Docker build environment\n├── .github/workflows/           # CI/CD pipelines\n└── platformio.ini               # Main PlatformIO configuration\n```\n\n---\n\n_This document was consolidated from `docs/project-summary.md` into the top-level `AGENTS.md` on 2026-07-11 to serve as the canonical repo orientation reference. It reflects the codebase as of the bugfix-2.1.x branch._\n","category":"root","tokens":7257}]}