📝 AGENTS.md for codebase and HALs

This commit is contained in:
Scott Lahteine 2026-07-16 00:08:45 -05:00
parent f44cb948c7
commit 2632e284a5
19 changed files with 1720 additions and 1 deletions

534
AGENTS.md Normal file
View file

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

169
Marlin/src/HAL/AGENTS.md Normal file
View file

@ -0,0 +1,169 @@
# AGENTS.md — HAL folder (Hardware Abstraction Layer)
Umbrella documentation for the entire `Marlin/src/HAL/` folder — the top-level HAL directory, **not** any single family subfolder. Per-family working notes live in each `Marlin/src/HAL/<FAMILY>/AGENTS.md` (e.g. `Marlin/src/HAL/STM32/AGENTS.md`). This file describes what the folder contains and how the HAL participates in Marlin's `inc/` include cascade and `ini` build-time source selection.
## What this folder contains
`Marlin/src/HAL/` is the root of Marlin's hardware abstraction layer. At the top level:
- **`HAL.h`** — the HAL dispatcher / entry point. It `#include "platforms.h"`, then pulls in the _active_ family's `HAL.h` via `#include HAL_PATH(.., HAL.h)` and declares the global `extern MarlinHAL hal;`. Defines a few cross-platform helpers (`HAL_ADC_RANGE`, `I2C_ADDRESS`, `S_FMT`, `PGMSTR`). See "Where the HAL sits in the inc/ include ordering" for how/when it is actually included into a translation unit.
- **`platforms.h`** — maps a compiler/board guard macro to a family folder. It defines the `HAL_PATH(PATH, NAME)` macro to stringize `PATH/HAL/<FAMILY>/NAME` for the currently-selected platform (see "HAL selection (platforms.h / guard macros)").
- **`shared/`** — cross-HAL APIs and helpers reused by every family: `eeprom_api.{h,cpp}`, `HAL_SPI.h`, `serial_ports.h`, `servo.{h,cpp}`, `servo_private.h`, `Marduino.h`, `math_32bit.h`, `progmem.h`, `Delay.{h,cpp}`, `MinSerial.{h,cpp}`, `fauxpins.h`, `HAL_ST7920.h`, `esp_wifi.{h,cpp}`, `eeprom_if*.{h,cpp}`, plus the `backtrace/` and `cpu_exception/` subfolders. Family HALs include these rather than reimplementing drivers.
- **`<FAMILY>/`** — one implementation folder per microcontroller family. Each contains that family's `HAL.h`/`HAL.cpp`, `MarlinHAL` subclass, timer/serial/SPI/fastio/servo code, an `inc/` subfolder (family-local `Conditionals*` and `SanityCheck.h`), and often an `eeprom/`, `u8g/`, and `tft/` subfolder.
The current family folders are:
```
AT32/ AVR/ DUE/ ESP32/ GD32_MFL/ HC32/ LINUX/ LPC1768/
NATIVE_SIM/ RP2040/ SAMD21/ SAMD51/ STM32/ STM32F1/
TEENSY31_32/ TEENSY35_36/ TEENSY40_41/
```
There is **no** `Marlin/src/HAL/inc/` subfolder at the HAL top level. Family-local `inc/` directories live _inside each family folder_ (e.g. `HAL/STM32/inc/SanityCheck.h`, `HAL/AT32/inc/Conditionals_adv.h`). The top-level shared include cascade lives in `Marlin/src/inc/`.
## HAL selection (platforms.h / guard macros)
`platforms.h` contains one `#if`/`#elif` chain keyed on compiler- or board-defined guard macros. The first matching branch defines `HAL_PATH(PATH, NAME)` to expand to `PATH/HAL/<FAMILY>/NAME`. The macros and their resolved folders (verified from `platforms.h`):
| Guard macro | Family folder |
| --------------------------------- | -------------------------------------- |
| `__AVR__` | `HAL/AVR` |
| `ARDUINO_ARCH_SAM` | `HAL/DUE` |
| `__MK20DX256__` | `HAL/TEENSY31_32` |
| `__MK64FX512__` / `__MK66FX1M0__` | `HAL/TEENSY35_36` |
| `__IMXRT1062__` | `HAL/TEENSY40_41` |
| `TARGET_LPC1768` | `HAL/LPC1768` |
| `ARDUINO_ARCH_HC32` | `HAL/HC32` |
| `ARDUINO_ARCH_MFL` | `HAL/GD32_MFL` |
| `__STM32F1__` / `TARGET_STM32F1` | `HAL/STM32F1` |
| `ARDUINO_ARCH_STM32` | `HAL/STM32` (also `#define HAL_STM32`) |
| `ARDUINO_ARCH_ESP32` | `HAL/ESP32` |
| `__PLAT_LINUX__` | `HAL/LINUX` |
| `__PLAT_NATIVE_SIM__` | `HAL/NATIVE_SIM` |
| `__SAMD51__` | `HAL/SAMD51` |
| `__SAMD21__` | `HAL/SAMD21` |
| `__PLAT_RP2040__` | `HAL/RP2040` |
| `ARDUINO_ARCH_AT32` | `HAL/AT32` |
If none match, `platforms.h` emits `#error "Unsupported Platform!"`. The guard macros are supplied by the Arduino core / toolchain / board JSON for the active environment, so the _compiler_ (not the build script) decides which family `HAL_PATH` points at.
> Note: `HAL_PATH` is a stringizing macro, so every "include the family file" line in the cascade uses `HAL_PATH(.., <name>)` rather than a literal path. The `..` argument is the relative path back to `Marlin/src/` from inside `Marlin/src/HAL/`.
## Build-time inclusion (ini build_src_filter)
The PlatformIO `default_src_filter` (defined in `platformio.ini`'s `[common]` section) starts from `+<src/*>` and then **excludes the whole HAL tree**:
```
default_src_filter = +<src/*> -<src/config> -<src/tests>
...
; Marlin HAL
-<src/HAL>
+<src/HAL/shared>
-<src/HAL/shared/backtrace>
-<src/HAL/shared/cpu_exception>
-<src/HAL/shared/eeprom_if_i2c.cpp>
-<src/HAL/shared/eeprom_if_spi.cpp>
...
```
So by default _no_ family folder is compiled (only `HAL/shared/` and a few named shared files survive). Each family's board environment re-enables exactly one family folder via its `build_src_filter`, e.g.:
- `ini/at32.ini` (`[AT32F403_base]`): `build_src_filter = ${common.default_src_filter} +<src/HAL/AT32>`
- `ini/avr.ini`: `+<src/HAL/AVR>`
- `ini/raspberrypi.ini`: `+<src/HAL/RP2040>`
- `ini/esp32.ini`: `+<src/HAL/ESP32>`
- `ini/lpc176x.ini`: `+<src/HAL/LPC1768> -<src/HAL/LPC1768/tft> +<src/HAL/shared/backtrace>`
- `ini/stm32f1-maple.ini`: `+<src/HAL/STM32F1> -<src/HAL/STM32F1/tft>`
Some environments additionally enable `src/HAL/shared/backtrace` or prune per-board subtrees (e.g. `-<src/HAL/LPC1768/tft>`, re-added selectively through `custom_marlin.*` switches). The net effect: at build time, only the _one active_ family folder plus the shared helpers are compiled — even though all families ship in the source tree.
## Layering: HAL vs pins vs boards
Three layers cooperate to bind a binary to a specific board:
1. **`Marlin/src/core/boards.h`** — selects the board. The active `MOTHERBOARD` define (from `Configuration.h` / `Config.h`) maps to a board header under `Marlin/src/pins/<family>/`, which in turn supplies `pins_arduino.h` (or equivalent) pin macros and the family's `HAL_PATH`-relevant defines.
2. **`Marlin/src/pins/<family>/`** — board pin maps (logical pin → MCU pin) for one family. These are data only; they do not implement behavior.
3. **`Marlin/src/HAL/<FAMILY>/`** — the _implementation_: timers, serial, SPI, fastio, EEPROM backends, `MarlinHAL` subclass, etc. This is the only layer that contains executable HAL logic.
The compiler guard macro in `platforms.h` (section above) decides which `HAL/<FAMILY>` directory the `HAL_PATH` macro resolves to; `core/boards.h` + `pins/` decide which pin table and which `MOTHERBOARD` apply; and `ini/*.ini` `build_src_filter` decides which family's `.cpp` files are actually passed to the compiler. They must agree for a build to be coherent.
## Where the HAL sits in the inc/ include ordering
Every Marlin translation unit includes `Marlin/src/inc/MarlinConfig.h` (or, for dependency-only scans, `MarlinConfigPre.h`). The cascade below is traced from the real files (`MarlinConfig.h`, `MarlinConfigPre.h`, `MarlinConfigPre-5-post.h`, `MarlinConfigPre-6-type.h`, `Conditionals-*`).
### Net ordered cascade
```
MarlinConfig.h
└─ Conditionals-6-type.h
└─ MarlinConfigPre-6-type.h
├─ Conditionals-5-post.h
│ ├─ MarlinConfigPre.h
│ │ ├─ Conditionals-1-axes.h
│ │ │ └─ MarlinConfigPre-1-axes.h
│ │ │ ├─ Config.h
│ │ │ ├─ macros.h
│ │ │ ├─ core/boards.h ← board selection
│ │ │ ├─ Configuration.h (if not Config.h)
│ │ │ ├─ HAL/platforms.h ← defines HAL_PATH macro + family
│ │ │ └─ Version.h
│ │ ├─ Conditionals-2-LCD.h
│ │ ├─ Conditionals-3-etc.h
│ │ ├─ Conditionals-4-adv.h
│ │ │ └─ MarlinConfigPre-4-adv.h
│ │ │ ├─ Conditionals-3-etc.h (re-included)
│ │ │ ├─ drivers.h
│ │ │ └─ Configuration_adv.h
│ │ └─ HAL_PATH(.., inc/Conditionals_adv.h) ← FAMILY conditionals
│ └─ (rest of Conditionals-5-post.h)
│ ├─ HAL_PATH(.., inc/Conditionals_post.h) ← FAMILY post-conditionals
│ └─ core/types.h
└─ MarlinConfigPre-5-post.h
├─ ../HAL/HAL.h ← HAL DISPATCHER (pulls family HAL.h via HAL_PATH;
│ declares `extern MarlinHAL hal;`)
├─ ../pins/pins.h ← board pin table
├─ HAL_PATH(.., timers.h)
└─ HAL_PATH(.., spi_pins.h)
(type-level conditionals defined in Conditionals-6-type.h)
MarlinConfig.h (resumes)
├─ HAL_PATH(.., inc/Conditionals_type.h) ← FAMILY type conditionals
├─ Changes.h
├─ core/language.h, core/utility.h, core/mstring.h, core/serial.h, core/endianness.h
├─ MarlinCore.h
├─ SanityCheck.h ← TOP-LEVEL src/inc/SanityCheck.h
└─ HAL_PATH(.., inc/SanityCheck.h) ← FAMILY sanity checks
```
Key points:
- **`HAL/platforms.h` is pulled in early** — inside `MarlinConfigPre-1-axes.h`, before any Conditionals run — so the `HAL_PATH` macro and the selected family are defined before anything else needs them.
- **`HAL.h` (the dispatcher) is included mid-cascade**, from `Marlin/src/inc/MarlinConfigPre-5-post.h` via `#include "../HAL/HAL.h"` (or `HAL/shared/fauxpins.h` when building with `__MARLIN_DEPS__`). This is the point where the family's own `HAL.h` (via `HAL_PATH(.., HAL.h)`) and the `MarlinHAL hal` instance become visible.
- **`pins.h` and the family `timers.h` / `spi_pins.h` are included immediately after `HAL.h`** in the same file, so pin and timer configuration are available before any module source compiles.
- **Family-local `inc/` files are included through `HAL_PATH(.., inc/<NAME>.h)`, never by literal path.** The top-level cascade includes the family's `inc/Conditionals_adv.h` (from `MarlinConfigPre.h`), `inc/Conditionals_post.h` (from `MarlinConfigPre-6-type.h`), and `inc/Conditionals_type.h` plus `inc/SanityCheck.h` (both from `MarlinConfig.h`). Each family provides whichever of these files it needs; missing ones simply aren't compiled.
### How the family SanityCheck is reached
`Marlin/src/inc/MarlinConfig.h` ends the cascade with (inside `#ifndef __MARLIN_DEPS__`):
```cpp
#include "SanityCheck.h" // Marlin/src/inc/SanityCheck.h (top-level)
#include HAL_PATH(.., inc/SanityCheck.h) // e.g. Marlin/src/HAL/STM32/inc/SanityCheck.h
```
So the _family_ sanity checks run **last**, after the top-level `SanityCheck.h` and after all `Conditionals-*`. The family file guards itself with `#pragma once` and family-specific `#ifdef` checks (e.g. the STM32/AT32 files open with `#ifndef PA0 #error "Your ARM platform pins are not defined as macros, only as enums!"`, forcing the board pin file to re-expose pins as numeric `#define`s). The top-level `src/inc/SanityCheck.h` may also reference HAL-specific macros and, where it does, point the reader to `HAL/<FAMILY>/inc/SanityCheck.h` for the platform-specific rule.
## Conventions
- The HAL top level is deliberately thin: `HAL.h` + `platforms.h` + `shared/` + the family folders. Do not add cross-family logic at the top level — put shared code in `HAL/shared/` and family-specific code in `HAL/<FAMILY>/`.
- Edit `Marlin/src/inc/*` (Conditionals/SanityCheck) only for _cross-family_ rules. Platform-specific checks belong in `HAL/<FAMILY>/inc/`.
- Keep board pin tables in `Marlin/src/pins/<family>/`; keep HAL behavior in `Marlin/src/HAL/<FAMILY>/`.
- When adding a new family, you must (a) add a branch to `platforms.h`, (b) create a `HAL/<FAMILY>/` tree with its own `HAL.h`/`MarlinHAL` and `inc/` files, and (c) add a `build_src_filter = ${common.default_src_filter} +<src/HAL/<FAMILY>>` to the family's `ini/*.ini` environment.
## Related
- Per-family docs: `Marlin/src/HAL/<FAMILY>/AGENTS.md` (e.g. `STM32/`, `AT32/`, `AVR/`, `ESP32/`, `RP2040/`, `LPC1768/`, `LINUX/`, `NATIVE_SIM/`, …).
- `Marlin/src/inc/MarlinConfig.h`, `MarlinConfigPre.h` — the include cascade.
- `Marlin/src/core/boards.h` — board selection; `Marlin/src/pins/` — board pin maps.
- `Marlin/src/HAL/shared/` — shared HAL APIs every family reuses.
- `platformio.ini` (`[common]` `default_src_filter`) and `ini/*.ini` — build-time family selection via `build_src_filter`.
- Wiki: [[marlin-src-hal]], [[hal-selection]], [[marlin-config-cascade]].

View file

@ -0,0 +1,53 @@
# AGENTS.md — AVR HAL
Working notes and conventions for the **AVR HAL** folder (`Marlin/src/HAL/AVR/`). This HAL covers the legacy 8-bit AVR microcontrollers (ATmega1280/2560/644/1284, AT90USB family) used on classic boards (Arduino Mega, RAMBo, Sanguinololu, Melzi, MightyBoard). It is the tightest resource-constrained target in Marlin: 8-bit, no FPU, tiny RAM/flash.
## Build & Test Loop
Validate with `mftest` (it regenerates `Marlin/Configuration.h` per target, which raw `pio run -e` does not do reliably):
```bash
cd "$(git rev-parse --show-toplevel)"
buildroot/bin/mftest -t mega2560 -n1 -y # ATmega2560, 256 KB flash / 8 KB RAM — tightest constraint
buildroot/bin/mftest -t mega2560ext -n1 -y # ATmega2560, extended pins 70-85
buildroot/bin/mftest -t mega1280 -n1 -y # ATmega1280
buildroot/bin/mftest -t rambo -n1 -y # RepRap RAMBo (ATmega2560)
buildroot/bin/mftest -t sanguino644p -n1 -y # ATmega644p
buildroot/bin/mftest -t sanguino1284p -n1 -y # ATmega1284p
buildroot/bin/mftest -t melzi_optiboot -n1 -y # Melzi (ATmega1284p, optiboot)
```
All targets build from `ini/avr.ini` (`env:` sections). The ATmega2560 (8 KB RAM, 256 KB flash) is the tightest constraint — if it fits there, the 1284p/rambo builds will too, but watch **RAM**, not just flash. `melzi_optiboot` / `sanguino1284p_optimized` add size-saving flags (`-fno-split-wide-types -mcall-prologues`) because the 1284p is flash- starved.
> Do NOT use `rm -rf .pio/build/...` to force a rebuild — the cross-profile write guard blocks it and it is unsafe. Use `pio run -e <env> -t clean` or just let `mftest` rebuild.
## Framework / Platform Integration (upstream, NOT vendored)
Unlike AT32, the AVR Arduino core is the **upstream** PlatformIO `atmelavr@~4.0.1` platform and the stock Arduino AVR core — it is NOT vendored under `buildroot/share/PlatformIO/`. There is no "mirror to installed package" requirement. Marlin-specific glue lives only in this HAL folder and in `buildroot/share/PlatformIO/` scripts (e.g. `generic_create_variant.py` for the `MARLIN_MEGA_EXTENDED` / `MARLIN_MEGA1281` variants). Most build flags are set in `ini/avr.ini`, not a framework build script.
### Gotchas that are not obvious from the source
1. **Harvard architecture — `PROGMEM` is mandatory for read-only data.** AVR has separate flash and RAM; any string or table left in `.data`/`.bss` silently eats the ~8 KB RAM. `HAL.h` defines `PGMSTR(NAM,STR)` and `pgm_read_ptr` shims; `pinsDebug.h`, `pinsDebug_plus_70.h`, and `u8g/u8g_com_HAL_AVR_sw_spi.cpp` all read via `pgm_read_byte` / `pgm_read_word`. **Never put a lookup table or string literal in plain RAM on AVR — mark it `PROGMEM` and read it back with the `pgm_read_*` macros.**
2. **No FPU — float math is emulated in software and is slow + large.** AVR has no native float unit. `HAL/AVR/math.h` provides hand-written assembly fixed-point helpers (`MultiU24X32toH16`, `MultiU8X8toH8`) used in the stepper hot path. **Avoid `float`/ `double` in ISRs and step-timing code; prefer the fixed-point helpers or integer math, or the build will bloat and stutter.**
3. **`MARLIN_EEPROM_SIZE` comes from `E2END`.** `eeprom.cpp` derives `MARLIN_EEPROM_SIZE` as `E2END + 1` (the framework defines `E2END` per-MCU — 4095 on ATmega2560). There is **no external EEPROM backend** (no `I2C_EEPROM`/`SPI_EEPROM`/ `SDCARD_EEPROM_EMULATION`) auto-selected; AVR uses the MCU's internal EEPROM only. Writes are byte-diffed to limit wear, with `delay(2)` to dodge the watchdog.
4. **`SERIAL_PORT` (and `_2`/`_3`) must be 0–3, and USB-CDC is not the default.** AVR Marlin uses hardware UART, not USB-CDC, except on the AT90USB family (native USB; `USBCON` defined → `HardwareSerial`, and `BOARD_NO_NATIVE_USB` is NOT defined). For non-USBCON parts `HAL.h` pulls in `MarlinSerial.h` and enforces `WITHIN(SERIAL_PORT, 0, 3)` with `#error`. **Don't raise `SERIAL_PORT` past 3.**
5. **Optimization flags live in `ini/avr.ini`, not a framework script.** Unlike AT32, there is no vendored `platformio-build-arduino.py`. Size-saving flags are in the env definitions: `common_avr8` adds `-Wl,--relax`; `tuned_1284p` / `mega_extended_optimized` add `-fno-tree-scev-cprop -fno-split-wide-types -mcall-prologues`. Flash overflow on a 1284p board means reaching for those flags, not editing source.
6. **`freeMemory()` is a real symbol, not a macro.** `HAL.h` declares `extern "C" int freeMemory();` (defined in `Marlin/src/HAL/shared/`); the AVR build's SRAM pressure makes it the go-to diagnostic. The watchdog is a no-op unless `USE_WATCHDOG` is set (`watchdog_init`/`watchdog_refresh` are `IF_DISABLED(USE_WATCHDOG, {})`), and reset source is cleared via `MCUSR = 0`.
## Conventions
- The compiler guard macro is `__AVR__` (defined by the compiler, NOT `ARDUINO_ARCH_AVR` — `HAL/platforms.h` keys on `__AVR__`). Do not add `ARDUINO_ARCH_AVR` guards.
- Keep HAL changes in `Marlin/src/HAL/AVR/`; per-board pin maps live in `Marlin/src/pins/rambo/`, `Marlin/src/pins/mega/`, `Marlin/src/pins/sanguino/`, `Marlin/src/pins/melzi/`, etc. Build/variant glue goes in `buildroot/share/PlatformIO/` and `ini/avr.ini`.
- Fast I/O macros are in `fastio.h` with per-MCU `fastio/fastio_*.h` includes (1280, 1281, 168, 644, AT90USB). Servo timing lives in `ServoTimers.h`.
- Treat RAM as the scarce resource: prefer `PROGMEM`, fixed-point math, and the tuned build flags on 1284p-class targets.
## Related
- Wiki: [[hal-avr]], [[marlin-src-hal]].
- `Marlin/src/HAL/shared/` — shared HAL APIs the AVR HAL reuses (`eeprom_api`, `HAL_SPI`, serial hook).
- `ini/avr.ini` — all AVR env definitions and size-saving flags.

View file

@ -0,0 +1,56 @@
# AGENTS.md — DUE HAL
Working notes and conventions for the **DUE HAL** folder (`Marlin/src/HAL/DUE/`). Covers the Arduino Due and compatible boards built on the Atmel/Microchip **SAM3X8E** (ARM Cortex-M3).
## Build & Test Loop
Validate with `mftest` (it regenerates `Marlin/Configuration.h` per target, which raw `pio run -e` does not do reliably):
```bash
cd "$(git rev-parse --show-toplevel)"
buildroot/bin/mftest -t DUE -n1 -y # RAMPS4DUE_EFB, hardware UART (Serial)
buildroot/bin/mftest -t DUE_USB -n1 -y # RAMPS4DUE over native USB CDC
buildroot/bin/mftest -t DUE_archim -n1 -y # UltiMachine Archim 1/2 (SAM3X8E)
```
All three DUE-family envs live in `ini/due.ini` (`env:DUE`, `env:DUE_USB`, `env:DUE_archim`) and map to the PlatformIO `due`, `dueUSB`, and `marlin_archim` board JSONs. `DUE` (config-01 is the heaviest, with ABL/S-Curve/ExtUI/SD) is the broadest smoke test; Archim uses the upstream Arduino SAM variant shipped under `buildroot/share/PlatformIO/variants/` (see `board_build.variants_dir`).
> Verified in this environment (toolchain `toolchain-gccarmnoneeabi` + `framework-arduino-sam` installed): `mftest -t DUE_archim` **builds green** (~8.7 s, ~103 KB / 524 KB flash). `mftest -t DUE` **fails** with a pre-existing `SanityCheck.h` Serial-1 pin-conflict error (`Serial Port 1 pin D18 and/or D19 conflicts…`) in the RAMPS4DUE_EFB test config — not caused by this doc; investigate before relying on the plain `DUE` target.
> Do NOT use `rm -rf .pio/build/...` to force a rebuild — the cross-profile write guard blocks it and it is unsafe. Use `pio run -e <env> -t clean` or just let `mftest` rebuild.
## Framework / Platform Integration (upstream, NOT vendored)
Unlike AT32, the DUE build uses the **upstream Arduino SAM core** (`framework-arduino-sam`, pulled by the `atmelsam` PlatformIO platform and `toolchain-gccarmnoneeabi`). It is NOT vendored under `buildroot/share/PlatformIO/`, so there is no installed-package ↔ repo mirror step. Marlin-specific glue lives entirely in this HAL folder, plus:
- `Marlin/src/HAL/DUE/upload_extra_script.py` — Archim-specific upload hook (`env:DUE_archim`).
- `buildroot/share/PlatformIO/variants/` — Archim board variant.
Do not "fix" the SAM core in `~/.platformio/packages/framework-arduino-sam/`; any Marlin change belongs in `Marlin/src/HAL/DUE/` (or `src/pins/...` for boards).
### Gotchas that are not obvious from the source
1. **Native USB is a real CDC stack, not a UART emulation.** When `SERIAL_PORT == -1` (the `DUE_USB` env uses it), Marlin routes serial over the SAM3X native USB (`MarlinSerialUSB`). The USB stack is vendored from **Atmel ASF (2015)** in `usb/` and MUST be initialized — `HAL.cpp` calls `usb_task_init()` in `init()` and `usb_task_idle()` in `idletask()`. If `idletask()` doesn't run, USB never enumerates. See `usb/README.md` for the ASF provenance and upgrade caveats.
2. **USB interrupt race fix lives in `usb/uotghs_device_due.c`.** A fix was applied there to resolve a race that left interrupts asserted when freezing the peripheral clock — causing hangs and watchdog resets from an interrupt storm. Preserve that fix if you touch the USB driver.
3. **EEPROM backend is per-board, not auto-selected.** Marlin does NOT auto-pick an EEPROM backend for DUE. `eeprom/eeprom_flash.cpp` implements `FLASH_EEPROM_EMULATION` (diff-based, wear-leveled over flash page groups — see the header comment) and `eeprom/eeprom_wired.cpp` implements I²C/SPI (`I2C_EEPROM` / `SPI_EEPROM`). Each DUE board's pins file must `#define` the backend it wants; nothing selects one by default.
4. **Watchdog is configured at boot, overriding the Arduino runtime.** `HAL.cpp`'s `watchdogSetup()` runs before `setup()` and either enables the WDT (4 s, or 8 s with `WATCHDOG_DURATION_8S`) or fully disables it. On SAM3X, late watchdog init after hardware reset is unreliable, so it must happen this early. `due.ini` passes `-DWATCHDOG_PIO_RESET` so a WDT fault also resets the PIO controller.
5. **Clock is 84 MHz from a 12 MHz crystal (PLL).** `F_CPU` is 84 MHz; the stepper and temperature timers (`timers.h`, prescaler 2, `TC2`/`TC4`/`TC6` handlers) are derived from it. Don't assume 16 MHz AVR-style timing — PWM frequencies and `analogWrite` scaling differ.
6. **`pin_t` is `int8_t` and ADC is 10-bit / 3.3 V.** `HAL.h` sets `HAL_ADC_VREF_MV 3300`, `HAL_ADC_RESOLUTION 10`, and `analogInputToDigitalPin(p) = p<12 ? p+54 : -1`. DUE analog pins are mapped above the digital range; `M43`/`M42` pin math depends on this.
## Conventions
- All HAL source is guarded by `#ifdef ARDUINO_ARCH_SAM` (defined by the upstream SAM core / `atmelsam` platform — no `ini` flag needed for it).
- Keep HAL changes in `Marlin/src/HAL/DUE/` and board pin changes in `Marlin/src/pins/ramps4due/`, `Marlin/src/pins/archim/`, etc.
- The `usb/` subtree is vendored ASF — treat as fragile; bring Marlin-local fixes forward when comparing against newer ASF.
- Don't pin or vendor the toolchain casually: `due.ini` leaves a commented `platform_packages = toolchain-gccarmnoneeabi@1.120301.0` because the default resolves to an older GCC 7.2.1.
## Related
- `usb/README.md` in this folder — ASF source provenance and USB upgrade notes.
- Wiki: [[hal-due]], [[marlin-src-hal]].
- `Marlin/src/HAL/shared/` — shared HAL APIs (`eeprom_api`, SPI helpers) the DUE HAL reuses.

View file

@ -0,0 +1,66 @@
# AGENTS.md — ESP32 HAL
Working notes and conventions for the **ESP32 HAL** folder (`Marlin/src/HAL/ESP32/`). This HAL runs Marlin on Espressif ESP32 (Xtensa) boards, using I2S-DMA stepper pulse generation, an optional serial I/O expander, and optional WiFi/OTA/Web support.
## Build & Test Loop
Validate with `mftest` (it regenerates `Marlin/Configuration.h` per target, which raw `pio run -e` does not do reliably):
```bash
cd "$(git rev-parse --show-toplevel)"
buildroot/bin/mftest -t esp32 -n1 -y # BOARD_ESPRESSIF_ESP32, WIFISUPPORT+WEBSUPPORT+OTA
buildroot/bin/mftest -t esp32 -n2 -y # BOARD_ESPRESSIF_ESP32, TMC HW serial (Serial1)
buildroot/bin/mftest -t mks_tinybee -n1 -y # BOARD_MKS_TINYBEE, ESP3D_WIFISUPPORT
```
Both `esp32` test targets exercise the base `env:esp32` build; `mks_tinybee` exercises the `ESP3D_WIFISUPPORT` path. Additional `ini/esp32.ini` envs with no test folder — `FYSETC_E4`, `PANDA`, `godi_esp32` — can be built directly with `pio run -e <env> -y` to check their partition-table / EXIO variants.
> Builds are **not verified in this environment** (the `espressif32` PlatformIO platform may not be installed here). Run the `mftest` commands above to validate; do not claim green without running them.
>
> Do NOT use `rm -rf .pio/build/...` to force a rebuild — the cross-profile write guard blocks it and it is unsafe. Use `pio run -e <env> -t clean` or just let `mftest` rebuild.
## Framework / Platform Integration (upstream, NOT vendored)
ESP32 uses the **upstream `espressif32` PlatformIO platform** (`espressif32@2.1.0`, toolchain `toolchain-xtensa-esp32s3`) plus the upstream Arduino-ESP32 / ESP-IDF libraries. There is **no Marlin-vendored core** (AT32 is the exception). All Marlin-specific glue lives in:
- `Marlin/src/HAL/ESP32/` — HAL implementation, I2S stepper, WiFi, OTA, SPIFFS, serial.
- `Marlin/src/pins/esp32/` — board pin tables (each pins file declares its `env:`).
- `ini/esp32.ini` — env defs, partition CSV selection, build flags.
Because the framework is upstream, there is **no "mirror to installed package" step** — just edit the repo files and rebuild.
### Gotchas that are not obvious from the source
1. **Marlin runs on the Arduino "app" core, not alone.** The I2S stepper task is pinned to `CONFIG_ARDUINO_RUNNING_CORE` via `xTaskCreatePinnedToCore(...)` in `i2s.cpp:343`. The chip is dual-core; do not assume single-core timing and avoid long `portENTER_CRITICAL` sections that would stall the other core.
2. **`DELAY_CYCLES` can pause prints for ~17.9 s.** The cycle-delay loop in `HAL.h` reads the `ccount` cycle counter and is vulnerable to overflow if a long FreeRTOS preemption/ISR lands mid-delay (it re-loops until `ccount` passes `stop`). This has caused real, apparently-random print stalls. The code already guards the overflow case — preserve that logic; do not "simplify" it.
3. **`MYSERIAL1` is `flushableSerial`, not the USB `Serial`.** `HAL.h` defines `MYSERIAL1 flushableSerial` (`FlushableHardwareSerial.h`). On ESP32 the bare `Serial` is USB/JTAG CDC; Marlin's G-code link is a hardware UART (Serial1 by default). Do not confuse the two. TMC HW-serial remaps Serial1/Serial2 to user pins in `HAL.cpp init_board()`.
4. **ADC2 is unusable while WiFi is active.** `HAL.cpp adc_init()` only configures ADC1 channels (`get_channel()` maps pins 32–39); ADC2 is shared with the WiFi radio and is intentionally left unconfigured (see comment at `HAL.cpp:253`). Keep thermistor pins on ADC1, or readings will fail when WiFi is up.
5. **Partition table is per-board and matters.** `env:esp32`/`mks_tinybee` use the platform default CSV; `FYSETC_E4` uses `default_16MB.csv`; `PANDA` and `godi_esp32` use the custom `Marlin/src/HAL/ESP32/esp32.csv` (otadata + two OTA app slots of 0x180000 + a SPIFFS partition). `WEBSUPPORT` needs the SPIFFS partition — if you change flash layout, keep the board's partition CSV in sync or OTA/Web won't fit.
6. **Two mutually-exclusive stepper backends.** `I2S_STEPPER_STREAM` (DMA-driven I2S GPIO expander, the default) and `USE_ESP32_EXIO` (serial I/O expander, used by PANDA). `i2s.cpp` is compiled only when `!USE_ESP32_EXIO`. Do not enable both; expander-pin PWM (pin > 127) is routed through the I2S path in `HAL.cpp` `set_pwm_duty`.
7. **EEPROM auto-selects the Arduino `EEPROM` class.** `eeprom.cpp` backs `PersistentStore` with the ESP32 `EEPROM` NVS emulation (`MARLIN_EEPROM_SIZE` = 4 KB, `EEPROM.begin()` / `EEPROM.end()`). No per-board `SDCARD_EEPROM_EMULATION` / `I2C_EEPROM` define is required (unlike AT32).
8. **Hardware-PWM pins are GPIO 0–33 only.** `MAX_PWM_IOPIN = 33` in `HAL.h`; `get_pwm_channel()` (HAL.cpp) rejects pins ≥ 34 (input-only) and caps at 15 LEDC channels. Pins 34–39 are input-only on ESP32 — never assign them to heater/fan PWM.
9. **Watchdog is split and partly stubbed.** `USE_WATCHDOG` refreshes the ESP task WDT via `esp_task_wdt_reset()`, but `MarlinHAL::watchdog_init()` is an explicit TODO stub. Separately, `USE_ESP32_TASK_WDT` inits a 10 s task WDT in `init_board()`. Don't rely on `watchdog_init()` doing setup.
10. **WiFi builds are size-sensitive.** `WIFISUPPORT` pulls ESPAsyncWebServer + Wi-Fi; `ESP3D_WIFISUPPORT` pulls esp3dlib. `ini/esp32.ini` sets `-DCORE_DEBUG_LEVEL=0` to keep the image small, and `mks_tinybee` adds `build_src_flags = -O3`. If a WiFi-enabled config overflows, check the partition CSV and debug level before touching HAL code.
## Conventions
- All HAL source is guarded by `#ifdef ARDUINO_ARCH_ESP32`.
- Keep HAL changes in `Marlin/src/HAL/ESP32/` and board pin changes in `Marlin/src/pins/esp32/`. Build/partition/env glue goes in `ini/esp32.ini`.
- The framework is upstream — edit repo files and rebuild; there is no vendored package to mirror.
- Don't enable both `I2S_STEPPER_STREAM` and `USE_ESP32_EXIO`; don't put thermistor pins on ADC2 when WiFi is in use; don't assign heater/fan pins ≥ 34.
## Related
- No `README.md` in this folder.
- Wiki: [[hal-esp32]], [[marlin-src-hal]].
- `Marlin/src/HAL/shared/` — shared HAL APIs (`eeprom_api`, SPI helpers) the ESP32 HAL reuses.
- `ini/esp32.ini` — env/partition/flag definitions for all ESP32 boards.

View file

@ -0,0 +1,60 @@
# AGENTS.md — GD32_MFL HAL
Working notes and conventions for the **GD32_MFL HAL** folder (`Marlin/src/HAL/GD32_MFL/`).
This HAL targets GigaDevice GD32F1/GD32F3 MCUs via the third-party **MFL Arduino Core** (`https://github.com/bnmguy/ArduinoCore_MFL`), not the older Maple/STM32duino cores. It currently supports the GD32F303RE (Creality V4.2.x) and GD32F103RC (Aquila v1.0.1) boards.
## Build & Test Loop
Always validate with `mftest` (it regenerates `Marlin/Configuration.h` per target, which raw `pio run -e` does not do reliably):
```bash
cd "$(git rev-parse --show-toplevel)"
buildroot/bin/mftest -t GD32F303RE_creality_mfl -n1 -y # GD32F303RE, 512 KB flash
buildroot/bin/mftest -t GD32F103RC_aquila_mfl -n1 -y # GD32F103RC, 256 KB flash
```
The Aquila (`GD32F103RC`, 256 KB) build is the tighter flash constraint — if it fits there, the Creality (512 KB) build will too. Both use a 0x7000 bootloader offset, so the linked firmware image reserves space below 0x08007000.
> Do NOT use `rm -rf .pio/build/...` to force a rebuild — the cross-profile write guard blocks it and it is unsafe. Use `pio run -e <env> -t clean` (removes only build artifacts) or just let `mftest` rebuild.
## Framework / Platform Integration (upstream, not vendored)
The MFL framework is **upstream**, pulled from a release ZIP (`platform = https://github.com/bmourit/platform-mfl/archive/refs/tags/V1.0.4.zip`) in `ini/gd32.ini`. It is **not** Marlin-vendored like AT32 — there is no `buildroot/share/PlatformIO/framework-arduino-*` to keep in sync, so the AT32 "mirror to installed package" warning does NOT apply. Marlin-specific glue lives entirely in this `HAL/GD32_MFL/` folder and in `ini/gd32.ini` / `buildroot/share/PlatformIO/` scripts (e.g. `offset_and_rename.py`).
Key `gd32_base` settings (`ini/gd32.ini`):
- `board_build.core = gd32`, C++23 (`-std=gnu++23`; `-std=gnu++11/14/17` stripped).
- `-DARDUINO_ARCH_MFL` (the compiler guard macro), `-DPLATFORM_M997_SUPPORT`, `-DTIMER_IRQ_PRIORITY=12`, `-DADC_RESOLUTION=12`, `-DCORE_DEBUG`.
- Per-board: `-DGD32F303RE` / `-DGD32F103RC`, `-DTIMER_TONE=2 -DSS_TIMER=3 -DTIMER_SERVO=4 -DTRANSFER_CLOCK_DIV=8`, `board_build.offset = 0x7000`, `board_upload.offset_address = 0x08007000`, `board_build.rename = firmware-{time}.bin`.
### Gotchas that are not obvious from the source
1. **Pins must be numeric `#define`s, not `enum`s.** `inc/SanityCheck.h` (lines 27–29) hard-errors `#ifndef PA0` with _"Your ARM platform pins are not defined as macros, only as enums!"_. The MFL core's `variant.h` / `pins_arduino.h` (included via `fastio.h` and `HAL.h`) supplies `PA0`, `PC6`, … as macros. **If that error appears, fix it at the pin-define level (add the missing `#define` to the variant), never by deleting the SanityCheck guard.** This is the same class of bug that bit AT32.
2. **0x7000 bootloader offset is mandatory.** Both boards link with `board_build.offset = 0x7000` and upload to `0x08007000`; the `offset_and_rename.py` extra script also renames the artifact to `firmware-{time}.bin`. Removing the offset / the script bricks the image (it would overwrite the bootloader). Keep them.
3. **EEPROM backend is per-board / fallback, not auto-picked like STM32.** `inc/Conditionals_post.h` falls back to `SDCARD_EEPROM_EMULATION` when no real or emulated EEPROM is selected, and maps `I2C_EEPROM`/`SPI_EEPROM` → `USE_SHARED_EEPROM`. `FLASH_EEPROM_LEVELING` is explicitly unsupported (SanityCheck error). The two test boards enable `SDSUPPORT` + `EEPROM_SETTINGS`, so the fallback SD emulation is what is exercised — make sure `SDSUPPORT` is on wherever `SDCARD_EEPROM_EMULATION` is used.
4. **Serial uses hardware USART, not USB-CDC.** `MarlinSerial` wraps the MFL `UsartSerial` (`MarlinSerial.h`); `SERIAL_INDEX_MIN/MAX` = 0..4. `EMERGENCY_PARSER` works via `register_emergency_callback()`. There is no USB-CDC path for Marlin — do not add one. `SERIAL_STATS_MAX_RX_QUEUED` and `SERIAL_STATS_DROPPED_RX` are explicitly unsupported (SanityCheck errors) — don't enable them.
5. **ADC defaults to 16× hardware oversampling.** The MFL framework oversamples by default; for `GD32F303RE` the HAL sets `HAL_ADC_FILTERED`. `HAL_ADC_RESOLUTION` is 12 (from `-DADC_RESOLUTION=12`). Software oversampling in Marlin is disabled to avoid double-counting.
6. **C++23 only.** `gd32_base` forces `-std=gnu++23` and unflags the older standards. Don't reintroduce `gnu++11/14/17` and don't use constructs that break under gnu++23.
7. **Timer assignment is fixed per board.** `TIMER_TONE=2`, `SS_TIMER=3`, `TIMER_SERVO=4`, `TRANSFER_CLOCK_DIV=8`, `TIMER_IRQ_PRIORITY=12` are passed in `ini/gd32.ini`. Changing them shifts which hardware timers are used for toning, stepper ISR, and servo — verify pin/timer conflicts before editing.
## Conventions
- All HAL source is guarded by `#ifdef ARDUINO_ARCH_MFL` (defined in `ini/gd32.ini`, NOT by the core).
- Keep HAL changes in `Marlin/src/HAL/GD32_MFL/` and board pin changes in `Marlin/src/pins/gd32f1/` (Aquila) and `Marlin/src/pins/gd32f3/` (Creality). The Creality/Aquila pins files `#include` the matching STM32F1 Creality pins and add `ALLOW_GD32F3` — they are thin overlays, not full pin lists.
- `MarlinSPI = SPIClass` (from the MFL `<SPI.h>`); no special SPI glue is needed.
- `M997` in-application firmware update is supported (`PLATFORM_M997_SUPPORT`, `flashFirmware()` in `HAL.cpp`).
- Pin mappings reuse the STM32F1 Creality layout; treat them as verified for those boards only and don't "fix" them to match guesses without a source.
## Related
- `README.md` in this folder — overview and supported boards.
- Wiki: [[hal-gd32-mfl]], [[marlin-src-hal]].
- `Marlin/src/HAL/shared/` — shared HAL APIs (`eeprom_api`, SPI helpers) this HAL reuses.
- `ini/gd32.ini` — the env definitions and build flags for this family.

View file

@ -0,0 +1,71 @@
# AGENTS.md — HC32 HAL
Working notes and conventions for the **HC32 HAL** folder (`Marlin/src/HAL/HC32/`).
## Build & Test Loop
Always validate with `mftest` (it regenerates `Marlin/Configuration.h` per target, which raw `pio run -e` does not do reliably):
```bash
cd "$(git rev-parse --show-toplevel)"
buildroot/bin/mftest -t HC32F460C_aquila_101 -n1 -y # Voxelab Aquila V1.0.x, 256 KB flash
```
`HC32F460C_aquila_101` is the only in-repo test target for HC32 (board `BOARD_AQUILA_V101`, 256 KB flash, `HC32F460C` base → `maximum_size = 262144`). It must be green before considering HC32 work done. The Aquila (256 KB) build is the tighter constraint — the 512 KB variants (`HC32F460E_*`) will fit if this does.
> Do NOT use `rm -rf .pio/build/...` to force a rebuild — the cross-profile write guard blocks it and it is unsafe. Use `pio run -e <env> -t clean` (removes only build artifacts) or just let `mftest` rebuild.
## Framework / Platform Integration (upstream, not vendored)
Unlike AT32, the HC32 HAL uses **upstream (third-party) Arduino packages** pulled straight from GitHub by PlatformIO — there is **no vendored framework** in this repo (`buildroot/share/PlatformIO/` carries only `framework-arduino-at32f4` and `platform-at32`, nothing for HC32). `ini/hc32.ini` declares them as remote archives:
```ini
platform = https://github.com/shadow578/platform-hc32f46x/archive/1.1.1.zip
platform_packages = framework-hc32f46x-ddl@https://github.com/shadow578/framework-hc32f46x-ddl/archive/2.2.3.zip
framework-arduino-hc32f46x@https://github.com/shadow578/framework-arduino-hc32f46x/archive/1.3.1.zip
```
Implications:
- **Framework fixes are NOT made in this repo.** To change the core (flags, serial, USB, DDL/DDL options) you edit `ini/hc32.ini` `build_flags` / `board_build.*` keys, or pin a new upstream core tag. There is no `buildroot/share/PlatformIO/framework-arduino-hc32f4x` to keep in sync with an installed package — the AT32 "mirror the two copies" rule does **not** apply here.
- The core version is pinned and **enforced at compile time**: `inc/SanityCheck.h` requires `ARDUINO_CORE_VERSION_INT >= 1.1.0` (for `app_config.h`) and gates `SERIAL_DMA`, `EMERGENCY_PARSER`, and `SoftwareSerial` on core 1.2.0 / 1.3.1. Bumping the core tag is a real compatibility event — check the `ARDUINO_CORE_VERSION_INT` checks before doing so.
### Gotchas that are not obvious from the source
1. **Pins are an `enum`, not `#define`.** The upstream core defines `PA0`, `PB1`, … as a C `enum`. The C preprocessor cannot see `enum` values in `#if`, so `PIN_EXISTS(PA0)` evaluated `PA0` as `0` → false pin-conflict errors. `inc/SanityCheck.h` now hard-errors if `PA0` is not `#define`d: _"Your ARM platform pins are not defined as macros, only as enums! Provide pins_arduino.h to define the pins."_ The fix is at the pin-define level (a `pins_arduino.h` mapping enum → macro). **Do not "fix" the symptom by editing SanityCheck — fix it at the pin-define level.**
2. **`app_config.h` is injected into EVERY core source.** `board_build.app_config = Marlin/src/HAL/HC32/app_config.h` is force-included by the Arduino build script for all translation units. It re-configures the core/DDL from `Configuration.h`/`Configuration_adv.h` (`MARLIN_DEV_MODE` → `__DEBUG`/`__CORE_DEBUG`, `POSTMORTEM_DEBUGGING` → `CORE_DISABLE_FAULT_HANDLER`, `SERIAL_DMA` → `USART_RX_DMA_SUPPORT`). It also **`#define DISABLE_SERIAL_GLOBALS 1`** (the core's `Serial1`/`Serial2`/`Serial` globals are suppressed — Marlin defines its own `MarlinSerial`/`Serial` alias) and force-enables the custom `PANIC_ENABLE` panic handler (in `MinSerial.cpp`). Changing Marlin serial/panic behavior without touching `app_config.h` will silently mismatch the core.
3. **Hardware UART, not USB-CDC.** `MarlinSerial` derives from the core's `Usart` class (`drivers/usart/Usart.h`) — Marlin talks over hardware USART only. There is no USB-CDC serial class here. `SERIAL_INDEX_MIN=1`, `SERIAL_INDEX_MAX=4` (ports 1–4). The core's `SERIAL_STATS_MAX_RX_QUEUED` / `SERIAL_STATS_DROPPED_RX` are explicitly error-unsupported.
4. **Emergency parser hooks the USART RX ISR.** `HAL.h` declares `extern "C" void usart_rx_irq_hook(uint8_t ch, uint8_t usart);` (behind `ENABLED(EMERGENCY_PARSER)`). `SERIAL_DMA` + `EMERGENCY_PARSER` together require core `>= 1.2.0` (that release added `core_hook_usart_rx_irq`), else SanityCheck errors. Enable both with an older core at your peril.
5. **EEPROM backend is per-board, not auto-selected.** Marlin does NOT auto-pick an `EEPROM_*_EMULATION` backend. Three implementations ship in `eeprom/`: `eeprom_wired.cpp` (I2C/SPI wired), `eeprom_if_iic.cpp` (generic I2C), `eeprom_bl24cxx.cpp` (BL24Cxx I2C EEPROM), and `eeprom_sdcard.cpp` (`SDCARD_EEPROM_EMULATION`, requires `SDSUPPORT`). The board pins file must `#define` the backend it wants; the Aquila test uses SD-card EEPROM (`sdsupport = on`, `eeprom_settings = on`). `SDCARD_EEPROM_EMULATION` without `HAS_MEDIA` is an error.
6. **`FAST_PWM_FAN` is unsupported.** `inc/SanityCheck.h` hard-errors on `FAST_PWM_FAN` — there is no hardware PWM-fan implementation yet. Don't enable it; use software PWM fans.
7. **`NEOPIXEL_LED` (Adafruit) is unsupported** except on `MKS_MINI_12864_V3`; any other config is an error. `TEMP_SENSOR_SOC` requires `TEMP_SOC_PIN` defined and not a real GPIO pin. These are Marlin feature gaps specific to this HAL.
8. **No compile-time PWM check (`NO_COMPILE_TIME_PWM`).** `fastio.h` defines `NO_COMPILE_TIME_PWM` because PWM capability is discovered at runtime via the TimerA assignment table (`timera_get_assignment`), not via a pin macro. `PWM_PIN(IO)` calls `isAnalogWritePin(IO)` at runtime. Don't assume `analogWrite`-eligible pins are known at preprocessor time.
9. **Flash size / offset is board-specific and lives in `ini/hc32.ini`.** The Aquila uses `board_upload.offset_address = 0xC000` (bootloader start, also `secondary` boot mode to save ~1.4 KB by dropping the ICG); Ender-2-Pro uses `0x8000`; OpenHC32Boot builds use `0x4000`. `HC32F460C` = 256 KB (`maximum_size = 262144`), `HC32F460E` = 512 KB. The linker script / flash layout is supplied by the upstream platform, not vendored here.
10. **`-fno-signed-char` is required for meatpack.** `board_build.flags.common` forces `-fno-signed-char`; removing it breaks meatpack. The build also adds `-fno-threadsafe-statics`, `-fno-exceptions`, `-fno-rtti` (no C++ runtime features used by Marlin) and `-g3` (debug symbols only — does not affect binary size).
11. **DDL driver middleware is selected via `board_build.ddl.*` / `mw.*` keys.** The `ots`, `sdioc`, `wdt`, `timer0`, `timera` DDL modules and the `sd_card` middleware are pulled in through `ini/hc32.ini`. `sdio.cpp` (SD card over SDIO) depends on `ddl.sdioc` + `mw.sd_card`; dropping those breaks SD support. **Don't assume a peripheral driver exists unless its DDL/MW flag is enabled.**
## Conventions
- All HAL source is guarded by `#ifdef ARDUINO_ARCH_HC32` (added by `ini/hc32.ini` `-DARDUINO_ARCH_HC32`; `inc/SanityCheck.h` sanity-checks the env via `NOT_TARGET`).
- Keep HAL changes in `Marlin/src/HAL/HC32/` and board pin changes in `Marlin/src/pins/hc32f4/`. Build/platform integration changes (core version, DDL/MW flags, flash offsets) go in `ini/hc32.ini` — there is no vendored framework to edit.
- Pin mappings are board-specific; see `Marlin/src/pins/hc32f4/pins_AQUILA_101.h` and `pins_CREALITY_ENDER2P_V24S4.h`. Mark any pin as a placeholder if it is not verified against a schematic.
- When you change the upstream core version (the `*@https://...archive/X.Y.Z.zip` tags in `ini/hc32.ini`), re-check every `ARDUINO_CORE_VERSION_INT` gate in `inc/SanityCheck.h` (1.1.0 for `app_config.h`, 1.2.0 for `SERIAL_DMA`+`EMERGENCY_PARSER`, 1.3.1 for `SoftwareSerial`) and rebuild the test target.
## Related
- `README.md` in this folder — overview, "adding a board" guide, dependencies, documentation notes.
- `app_config.h` in this folder — the auto-included core/DDL config bridge.
- Wiki: [[hal-hc32]], [[marlin-src-hal]].
- `Marlin/src/pins/hc32f4/` — board pin files.
- `Marlin/src/HAL/shared/` — shared HAL APIs (`eeprom_api`, SPI helpers) the HC32 HAL reuses.
- `Marlin/src/HAL/AT32/AGENTS.md` — the younger sibling HAL, modeled on this one.

View file

@ -0,0 +1,66 @@
# AGENTS.md — LINUX HAL
Working notes and conventions for the **LINUX HAL** folder (`Marlin/src/HAL/LINUX/`).
## Build & Test Loop
The LINUX HAL is a **native host build** — there is no MCU and no Arduino framework. Marlin compiles as a regular C++ program (a console application) and runs on the host CPU. Always validate with `mftest` (it regenerates `Marlin/Configuration.h` per target, which raw `pio run -e` does not do reliably):
```bash
cd "$(git rev-parse --show-toplevel)"
buildroot/bin/mftest -t linux_native -n1 -y # host-native build, EEPROM enabled
buildroot/bin/mftest -t linux_native_test -n1 -y # build + Unity unit tests
```
The `linux_native` target (`buildroot/tests/linux_native/config-01.ini`, `BOARD_SIMULATED`, `EEPROM_SETTINGS` on) is the primary smoke target and must be green before considering LINUX work done. The `linux_native_test` target extends it with the PlatformIO Unity test framework (`+<test>` sources, `-Werror`) and is the one to run when changing HAL code that has unit tests.
> Do NOT use `rm -rf .pio/build/...` to force a rebuild — the cross-profile write guard blocks it and it is unsafe. Use `pio run -e <env> -t clean` (removes only build artifacts) or just let `mftest` rebuild.
## Framework / Platform Integration (native, not embedded)
This is a `platform = native` build (`ini/native.ini`, `[env:linux_native]`). There is **no Arduino core, no toolchain SDK, no vendored framework** — the only "platform" is the host's C++ compiler (`-std=gnu++17`), linked against `librt` / `libpthread`. The HAL selected by `__PLAT_LINUX__` (`HAL/platforms.h` maps `__PLAT_LINUX__` → `src/HAL/LINUX/`); it has no `ARDUINO_ARCH_*` define. `main()` lives in `main.cpp` (not Arduino's `setup()`/`loop()` shim) and spins up `std::thread`s for serial I/O and the simulation loop, then calls `setup()` / `loop()`.
Because it is a plain C++ program:
- `build_src_filter` adds `+<src/HAL/LINUX>` to the common filter; the rest of Marlin is compiled normally.
- `build_src_flags` adds `-IMarlin/src/HAL/LINUX/include` so the local `Arduino.h`, `serial.h`, and `pinmapping.h` are found ahead of any system headers.
- `-lrt -lpthread` are required link flags (timers/clock, threading).
- `HAS_LIBBSD` (macOS) provides `strlcpy`; on Linux the HAL falls back to a local `MarlinHAL::_strlcpy` (`HAL.h`/`HAL.cpp`), so no system lib is needed there.
### Gotchas that are not obvious from the source
1. **No real pins — GPIO is a software array.** `Gpio::pin_count = 255` (`hardware/Gpio.h`); pins are indices into an in-memory `pin_map[]` (`Gpio.cpp`), not physical lines. `fastio.h` macros (`READ_PIN`, `WRITE_PIN`, `SET_DIR_*`) all delegate to `Gpio::` static methods. `PIN_EXISTS`/`GET_PIN_MAP_INDEX` are pass-through identity ops; `PWM_PIN` and `INTERRUPT_PIN` always return `false`. Don't add hardware-specific pin logic here.
2. **Serial is virtual, via stdio.** `HalSerial` (`include/serial.h`) is a pair of `RingBuffer<uint8_t,128>` buffers. `main.cpp`'s `write_serial_thread` flushes the TX ring to `stdout` and `read_serial_thread` reads `stdin` (via `fgets`) into the RX ring. So G-code must be piped/entered on the process's stdin/stdout — there is no UART/USB device. `host_connected` starts `true`; `write()` busy-waits while the TX ring is full.
3. **EEPROM is a file on disk.** `eeprom.cpp` reads/writes `eeprom.dat` (4 KB, `MARLIN_EEPROM_SIZE = 0x1000`) in the current working directory via `fopen`. Settings persist across runs in that file, and a stale `eeprom.dat` in your CWD can mask config changes — delete it to get a fresh store. The buffer is the in-memory source of truth; `access_finish()` is what actually flushes to disk.
4. **No real ADC / PID feedback.** `MarlinHAL::adc_value()` synthesizes a 10-bit reading from the simulated GPIO bit value (`Gpio::get(pin) >> 2`). `main.cpp`'s `simulation_loop()` runs `Heater` (hotend/bed) and `LinearAxis` (X/Y/Z/E) objects that update pin state in software — this is the only "hardware" feedback loop, and it runs on its own thread alongside `loop()`.
5. **`main()` is excluded under `UNIT_TEST`.** `main.cpp` is wrapped in `#ifndef UNIT_TEST` (and `#ifdef __PLAT_LINUX__`). The `linux_native_test` env compiles the HAL as a library for Unity tests and does **not** link `main()` — so a test build "succeeds" without the console entry point. Don't add HAL runtime code that only runs from `main()` and expect it to execute under the test env.
6. **Threads + `yield()` model timing, not interrupts.** There are no real ISRs; `CRITICAL_SECTION_START/END` are empty, `isr_on/off` are no-ops, and `DELAY_CYCLES` is `Clock::delayCycles()`. The step/sim timing is driven by `Clock` (set to `F_CPU` in `main()`) and `HAL_timer_init()`, plus per-thread `std::this_thread::yield()`. Real-time behavior is approximate and host-load dependent.
7. **`freeMemory()` always returns 0.** Unlike embedded HALs, the LINUX HAL reports no meaningful free-SRAM figure (`HAL.cpp` returns `0`; `MarlinHAL::freeMemory()` wraps it). Don't key any logic off the returned heap value.
8. **`NUM_ANALOG_INPUTS` is fixed at 16.** `include/pinmapping.h` hard-codes 16 analog inputs mapped to the top of the 255-entry digital space (`analog_offset`). The analog index ↔ digital pin conversions are constexpr arithmetic, not a board-specific table.
9. **SD / media is file-based, not SPI.** There is no SD card controller; `spi_pins.h` still defines default `SD_SCK_PIN`/`SD_MISO_PIN`/`SD_MOSI_PIN` (50/51/52) and a `SOFTWARE_SPI` fallback, but actual media acts on the host filesystem. Treat SD operations as ordinary file I/O in the host environment.
10. **Optional GPIO/position CSV logging.** `#define GPIO_LOGGING` in `main.cpp` (off by default) attaches an `IOLoggerCSV` and writes `all_gpio_log.csv` / `axis_position_log.csv` into the CWD. It is a debugging aid only and adds filesystem side effects; leave it disabled unless actively tracing pin/axis activity.
## Conventions
- All HAL source is guarded by `#ifdef __PLAT_LINUX__` (not `ARDUINO_ARCH_*`). The licensing/skeleton header wraps every `.cpp` in this guard.
- Keep HAL changes in `Marlin/src/HAL/LINUX/` and its `hardware/`, `include/`, `inc/`, `u8g/` subfolders. There are no board pin files here — `BOARD_SIMULATED` is the only board and the pin map is the fixed software array.
- The build is host-native: no flash/linker-script constraints, no MCU family macros, no Arduino `Serial` object — `MYSERIAL1` is the `HalSerial`-backed `usb_serial` (`HAL.h`/`HAL.cpp`).
- `simulator_linux_*` envs in `ini/native.ini` are a _different_ target: they build the graphical `NATIVE_SIM` HAL (`src/HAL/NATIVE_SIM`, SDL2/GLM UI), **not** this LINUX HAL. Do not conflate the two — LINUX is the headless console build, NATIVE_SIM is the GUI simulator.
- When you change HAL code, run `linux_native` (and `linux_native_test` if unit tests are affected) and verify green before committing.
## Related
- `Marlin/src/HAL/NATIVE_SIM/` — the sibling GUI simulator HAL (SDL2/GLM), built via `simulator_linux_*` envs (distinct from this LINUX HAL).
- Wiki: [[hal-linux]], [[marlin-src-hal]].
- `Marlin/src/HAL/shared/` — shared HAL APIs (`eeprom_api`, SPI helpers, `Marduino.h`) that this HAL reuses.
- `ini/native.ini` — `[env:linux_native]` / `[env:linux_native_test]` definitions.
- `buildroot/tests/linux_native/config-01.ini` — the `BOARD_SIMULATED` + EEPROM test config.

View file

@ -0,0 +1,60 @@
# AGENTS.md — LPC1768 HAL
Working notes and conventions for the **LPC1768 HAL** folder (`Marlin/src/HAL/LPC1768/`). Covers the NXP LPC1768/LPC1769 family (ARM Cortex-M3) used on ReARM, Smoothieboard, BTT SKR 1.3/1.4, MKS SBASE, etc.
## Build & Test Loop
Validate with `mftest` (it regenerates `Marlin/Configuration.h` per target, which raw `pio run -e` does not do reliably):
```bash
cd "$(git rev-parse --show-toplevel)"
buildroot/bin/mftest -t LPC1768 -n1 -y # env LPC1768 — ReARM / RAMPS_14_RE_ARM boards
buildroot/bin/mftest -t LPC1769 -n1 -y # env LPC1769 — Smoothieboard, etc.
```
Both targets should be green before considering LPC1768 work done. `LPC1768` is the primary/most-used env (both MCUs share 512 KB flash / 64 KB RAM; LPC1769 just clocks higher). Pick the individual test with `-n` (e.g. `-n1` … `-n5`); `LPC1768/config-01.ini` is ReARM EFB + VIKI2 + SD + NeoPixel + dual stepper.
> Do NOT use `rm -rf .pio` to force a rebuild — the cross-profile write guard blocks it and it is unsafe. Use `pio run -e <env> -t clean` or just let `mftest` rebuild.
## Framework / Platform Integration (upstream community core, not vendored)
The LPC176x support is **not** a Marlin-vendored framework. `ini/lpc176x.ini` pulls an upstream **community** Arduino core from GitHub:
- `platform = https://github.com/p3p/pio-nxplpc-arduino-lpc176x/archive/0.1.3.zip`
- `framework-arduino-lpc176x@https://github.com/p3p/pio-framework-arduino-lpc176x/archive/ab41696b64.zip`
- `toolchain-gccarmnoneeabi@1.100301.220327`
These land in `~/.platformio/packages/…` as normal PlatformIO packages — there is no copy under `buildroot/share/PlatformIO/`, so the AT32 "mirror to installed package" warning does NOT apply here. Marlin-specific glue lives entirely in this HAL folder plus `Marlin/src/pins/lpc1768/`. Build flags of note: `-std=gnu++20 -Wno-volatile -DU8G_HAL_LINKS -DPLATFORM_M997_SUPPORT`, and `build_src_filter` excludes `src/HAL/LPC1768/tft` by default (selected per-board via `custom_marlin.HAS_SPI_TFT`).
### Gotchas that are not obvious from the source
1. **Guard macro is `TARGET_LPC1768`, not `ARDUINO_ARCH_*`.** It is defined by the platform/board JSON, not by the core. Every file in this HAL is wrapped in `#ifdef TARGET_LPC1768`, and `HAL/platforms.h` selects `HAL/LPC1768` on that macro. `LPC1769` builds compile the _same_ folder (the MCU difference is handled inside the core, e.g. `isLPC1769()` in `HAL.cpp`).
2. **The default `Serial` is USB-CDC, not a UART.** `MarlinSerial.h` defines `USB_SERIAL_PORT(...) USBSerial` where `USBSerial` is a `ForwardSerial1Class<UsbSerial>` over the USB CDC stack (`usb_serial.cpp`, `cdcuser.h`). Hardware UARTs `MSerial0..3` (UART0–UART3) are defined separately in `MarlinSerial.cpp` behind `USING_HW_SERIALx`. Boards that want UART-as-primary must route a hardware serial to `Serial`.
3. **`HardwareSerial` interface mismatch → `ForwardSerial1Class` wrapper.** The core's `HardwareSerial` does not implement Arduino's `Serial` overloads, so `MarlinSerial.h` wraps `MarlinSerial` in a `ForwardSerial1Class<MarlinSerial>` (`MSerialT`) and warns in comments. Because of that, `SERIAL_RUNTIME_HOOK` is explicitly unsupported here — `MarlinSerial.h` has `#error "SERIAL_RUNTIME_HOOK is not yet supported for LPC176x."`
4. **EEPROM backend is per-board, never auto-selected.** Three backends ship in `eeprom/`, each gated by a define the board/pins file must set: `eeprom_wired.cpp` (`USE_WIRED_EEPROM`), `eeprom_sdcard.cpp` (`SDCARD_EEPROM_EMULATION`), `eeprom_flash.cpp` (`FLASH_EEPROM_EMULATION`). Most boards use `SDCARD_EEPROM_EMULATION` (e.g. `pins_BTT_SKR_V1_4.h` selects it over `I2C_EEPROM`). Marlin will not pick one for you — forgetting the define yields no settings storage.
5. **Flash EEPROM uses IAP on sector 29 with wear-leveling.** `eeprom_flash.cpp` reserves a 32 KB sector and writes 4 KB "slots" in turn, erasing the whole sector only when all slots are used. It holds a `ram_eeprom[]` image and disables IRQs around the IAP calls (`lpc17xx_iap.h` `CopyRAM2Flash`/`EraseSector`). Don't touch the IAP critical sections.
6. **Hardware-SPI pins can't be bit-banged while the SSP is active.** `HAL_SPI.cpp` documents that SCK/MOSI/MISO cannot be set with `WRITE`/`digitalWrite` once the LPC17xx SSP module is on; if the LCD and SD share those pins you MUST use `SOFTWARE_SPI`. The global `SPI` object is instantiated in `HAL_SPI.cpp` keyed off `SD_MISO_PIN` matching `BOARD_SPI1_MISO_PIN`/`BOARD_SPI2_MISO_PIN`.
7. **Firmware update (M997) works via USB reconnect + NVIC reset.** `HAL.cpp` `flashFirmware()` does `USB_Connect(false)`, delays, then `hal.reboot()` (`NVIC_SystemReset()`). `PLATFORM_M997_SUPPORT` is forced on in `HAL.h`. Upload itself is mass-storage copy: `upload_extra_script.py` auto-finds the `REARM` volume or a `FIRMWARE.CUR` file and sets `upload_port` — manual copy of `.pio/build/<env>/firmware.bin` also works.
8. **All pins are PWM-capable; ADC is median-filtered.** `fastio.h` sets `PWM_PIN(P) true` and `HAL.h` defines `HAL_CAN_SET_PWM_FREQ`. ADC uses a median filter (`ADC_MEDIAN_FILTER_SIZE 23`) + low-pass (`ADC_LOWPASS_K_VALUE 2`) and is already filtered in-HAL (`HAL_ADC_FILTERED`), so don't re-filter upstream.
9. **Onboard-SD pins are sensitive.** `HAL.h` declares `HAL_SENSITIVE_PINS P0_06, P0_07, P0_08, P0_09` (the MCU's onboard SD bus) — M42/M43 must not let these be toggled.
## Conventions
- All HAL source is guarded by `#ifdef TARGET_LPC1768` (set by the platform, not the core).
- Keep HAL changes in `Marlin/src/HAL/LPC1768/`; board pin changes in `Marlin/src/pins/lpc1768/`. Build-root integration (`ini/lpc176x.ini`, `upload_extra_script.py`) is the only place for build/upload tweaks.
- The core is an upstream p3p package, not a Marlin-vendored one — no `buildroot/share/PlatformIO` mirror step is needed. Fixes to the core itself must be upstreamed to p3p's repos, not patched in-tree.
- Don't "fix" missing `Serial`/EEPROM behavior in `SanityCheck` — solve it at the pin/ backend level in the board's pins file.
## Related
- `Marlin/src/pins/lpc1768/` — board pin definitions (ReARM, Smoothieboard, SKR, SBASE…).
- Wiki: [[hal-lpc1768]], [[marlin-src-hal]].
- `Marlin/src/HAL/shared/` — shared HAL APIs (`eeprom_api`, `HAL_SPI`, `serial_ports`) reused here.

View file

@ -0,0 +1,81 @@
# AGENTS.md — NATIVE_SIM HAL
Working notes and conventions for the **NATIVE_SIM HAL** folder (`Marlin/src/HAL/NATIVE_SIM/`).
## Build & Test Loop
NATIVE_SIM is a **native host simulator with a GUI** — there is no MCU, no Arduino framework, and no embedded toolchain. Marlin compiles as a regular C++ program (`platform = native`, `ini/native.ini`, `[simulator_common]`) that renders a printer UI on the host using SDL2 / SDL2_net / OpenGL / GLM. Always validate with `mftest` (it regenerates `Marlin/Configuration.h` per target, which raw `pio run -e` does not do reliably):
```bash
cd "$(git rev-parse --show-toplevel)"
buildroot/bin/mftest -t simulator_linux_release -n1 -y # Linux GUI simulator (primary)
buildroot/bin/mftest -t simulator_linux_debug -n1 -y # Linux GUI simulator, debug build
# On macOS:
buildroot/bin/mftest -t simulator_macos_release -n1 -y
# On Windows (MSYS2):
buildroot/bin/mftest -t simulator_windows -n1 -y
```
The `simulator_linux_release` target (`buildroot/tests/simulator_linux_release/config-01.ini` → `ini_use_config = example/Simulator`, `BOARD_SIMULATED`) is the canonical smoke target and must be green before considering NATIVE_SIM work done.
> `mftest` only **builds** the simulator — it does not launch it. The produced binary (`MarlinSimulator`, see below) needs a graphical session (X11 / macOS window server) to actually run, so a build that links clean here can still require a desktop to exercise the UI. Don't expect `mftest` to "run" the firmware.
>
> Do NOT use `rm -rf .pio/build/...` to force a rebuild — the cross-profile write guard blocks it and it is unsafe. Use `pio run -e <env> -t clean` (removes only build artifacts) or just let `mftest` rebuild.
## Framework / Platform Integration (native, GUI — distinct from LINUX)
This is a `platform = native` build, but unlike the **LINUX** HAL (a headless console app that talks over stdin/stdout), NATIVE_SIM is the **graphical** simulator. The HAL is selected by `__PLAT_NATIVE_SIM__` (`HAL/platforms.h` maps `__PLAT_NATIVE_SIM__` → `src/HAL/NATIVE_SIM/`); it has no `ARDUINO_ARCH_*` define. There is **no vendored Arduino core, no MCU SDK** — the only "platform" is the host C++ compiler (`-std=gnu++17`).
The native GUI / Arduino-shim headers are **not** in this folder and **not** in `HAL/LINUX/include`. They are pulled in at build time from the `MarlinSimUI` library dependency (a pinned GitHub zip in `[simulator_common]` `lib_deps`, plus `Adafruit NeoPixel` and `LiquidCrystal` zips). `MarlinSimUI` supplies `Arduino.h`, `serial.h`, `pinmapping.h`, and the `Gpio` class — so `HAL.h`'s `#include "serial.h"` and `fastio.h`'s `#include <pinmapping.h>` resolve against _that_ library, not local or LINUX files. The `MarlinSimulator` program entry point (`main()`) also lives in `MarlinSimUI`, **not** in `src/HAL/NATIVE_SIM/` — there is no `main.cpp` here.
The build is wired by:
- `[simulator_common]` (`ini/native.ini`): `platform = native`, `-D__PLAT_NATIVE_SIM__ -DU8G_HAL_LINKS -DGLM_ENABLE_EXPERIMENTAL`, `build_src_filter = ... +<src/HAL/NATIVE_SIM>`, `lib_deps` (MarlinSimUI + others), and `pre:buildroot/share/PlatformIO/scripts/simulator.py`.
- `simulator.py`: renames the binary to `MarlinSimulator`, and on macOS **fails the build** if `/usr/bin/gcc` (Apple clang) is the compiler — it requires a real GCC from MacPorts/Homebrew (`gcc14`) plus Mesa/SDL2.
Required host libraries (from `native.ini` comments):
- Linux: `libsdl2-dev`, `libsdl2-net-dev`, `libglm-dev` (and `python3-venv`, `build-essential`).
- macOS: MacPorts or Homebrew `gcc@14`, `glm`, `mesa`, `sdl2`, `sdl2_net`.
- Windows: MSYS2 `mingw-w64-x86_64` toolchain + `glm`, `SDL2`, `SDL2_net`, `dlfcn`.
### Gotchas that are not obvious from the source
1. **No MCU, no real pins — GPIO is a software array.** `fastio.h` macros (`READ_PIN`, `WRITE_PIN`, `SET_DIR_*`, `SET_MODE`) all delegate to a `Gpio` class that operates on an in-memory `pin_map[256]` (`Gpio::pin_count = 255`, matching the LINUX HAL model). There are no physical lines; `PWM_PIN`/`INTERRUPT_PIN` effectively never fire. Do not add hardware-specific pin logic here — this is the same virtual-pin model as the LINUX HAL, just with a GUI on top.
2. **No real interrupts / ISRs.** `CRITICAL_SECTION_START/END` are empty, `isr_on/off` are no-ops, and `DELAY_CYCLES` is a software delay. Endstop/timer "hardware" events are driven by the simulator's own loop (MarlinSimUI), not by vector interrupts. Don't write ISR-dependent timing assumptions into HAL code.
3. **Serial is virtual over the host process.** `HAL.h` declares `MSerialT serial_stream_0..3` (`SERIAL_INDEX_MIN/MAX` 0..3) and `serial.h` (from MarlinSimUI) defines `MSerialT` as `Serial1Class<HalSerial>` — ring-buffer-backed virtual ports. G-code is exchanged with the `MarlinSimulator` process's stdin/stdout, not a UART/USB device. There is no `Serial` USB-CDC object.
4. **Arduino/serial/pinmapping/Gpio headers come from MarlinSimUI, not this folder.** A HAL change that _looks_ like a missing local header (e.g. `serial.h`, `pinmapping.h`, `Gpio.h`) is actually supplied by the downloaded library dependency. If a build fails with "header not found", suspect a `lib_deps` fetch failure or a `simulator.py`/GCC mismatch — not a missing file in `src/HAL/NATIVE_SIM/`.
5. **The GUI entry point is external.** There is no `main.cpp` in this HAL. `MarlinSimUI` provides `main()` and the SDL2 event/render loop; `simulator.py` sets `PROGNAME = "MarlinSimulator"`. HAL code here runs _inside_ that host GUI program — don't add process entry points or assume `setup()`/`loop()` are the only callers.
6. **macOS requires real GCC, not Apple clang.** `simulator.py` hard-fails when `/usr/bin/gcc` (which is clang) is on PATH; you must `port install gcc14 ...` or `brew install gcc@14 ...` and symlink `gcc`/`g++` to `gcc-14`/`g++-14`. Linux/Windows use their respective native GCC/MinGW toolchains. A "can't build on macOS" symptom is almost always this GCC-vs-clang issue, not a HAL bug.
7. **`NO_COMPILE_TIME_PWM` is set in `fastio.h`.** PWM duty is computed at runtime via `MarlinHAL::set_pwm_duty()` (`map(v, 0, v_size, 0, UINT16_MAX)` → `analogWrite`), so there are no compile-time PWM pin tables. Don't add `PWM`/compile-time duty logic.
8. **Display layer is software-SPI u8g, not hardware.** `u8g/u8g_com_sw_spi.cpp`, `u8g_com_st7920_sw_spi.cpp`, and the `LCD_*` routines implement bit-banged SPI that the simulator renders into its GUI window. The `build_flags` carry `-DU8G_HAL_LINKS`; the drawing ultimately goes through U8glib-HAL in the MarlinSimUI host. Treat these as rendering shims, not real bus drivers.
9. **No local `eeprom.cpp` / `main.cpp`.** Unlike the LINUX HAL (which has its own `eeprom.cpp` writing `eeprom.dat`), NATIVE_SIM has no EEPROM file in this folder — persistence uses the shared `HAL/shared` EEPROM API mediated by the simulator host. A "missing eeprom" symptom points at the shared API or MarlinSimUI, not a missing `src/HAL/NATIVE_SIM` file.
10. **`freeMemory()` is a stub.** Per `HAL.h`, `MarlinHAL::freeMemory()` and `::freeMemory()` are placeholders (no meaningful host heap figure). Don't key any logic off the returned value.
## Conventions
- All HAL source is guarded by `#ifdef __PLAT_NATIVE_SIM__` (not `ARDUINO_ARCH_*`). Every `.cpp` wraps its body in this guard (see `HAL.cpp`, `pinsDebug.cpp`, `Servo.cpp`).
- Keep HAL changes in `Marlin/src/HAL/NATIVE_SIM/` and its `u8g/`, `tft/`, `inc/` subfolders. Board pin layout is `Marlin/src/pins/native/pins_RAMPS_NATIVE.h` (`BOARD_SIMULATED`, a RAMPS-like map) — not in this folder.
- This is the **GUI** simulator; the **LINUX** HAL (`src/HAL/LINUX/`, `linux_native` env) is the separate headless console build. Do not conflate the two. Both share the same virtual-`Gpio` pin model, so a pin/simulation fix may need to be mirrored in the LINUX HAL too.
- External dependencies (`MarlinSimUI`, `Adafruit NeoPixel`, `LiquidCrystal`) are pinned git-zip `lib_deps`; if you change a HAL API they call, bump/verify the library version and re-test the build.
- When you change HAL code, run `simulator_linux_release` (and the platform you develop on) and verify green before committing.
## Related
- `Marlin/src/HAL/AT32/AGENTS.md` — the precedent for this file's structure.
- `Marlin/src/HAL/LINUX/AGENTS.md` — the sibling headless console simulator (shared virtual-`Gpio` model, distinct build).
- Wiki: [[hal-native-sim]], [[marlin-src-hal]], [[hal-linux]].
- `Marlin/src/HAL/shared/` — shared HAL APIs (`eeprom_api`, SPI helpers, `Marduino.h`) reused by this HAL.
- `ini/native.ini` — `[simulator_common]` / `simulator_linux*` / `simulator_macos*` / `simulator_windows` env definitions.
- `buildroot/tests/simulator_linux_release/config-01.ini` — the `BOARD_SIMULATED`
- `example/Simulator` test config.
- `buildroot/share/PlatformIO/scripts/simulator.py` — pre-build script (binary rename, macOS GCC/OpenGL checks).

View file

@ -0,0 +1,55 @@
# AGENTS.md — RP2040 HAL
Working notes and conventions for the **RP2040 HAL** folder (`Marlin/src/HAL/RP2040/`).
## Build & Test Loop
Validate with `mftest` (it regenerates `Marlin/Configuration.h` per target, which raw `pio run -e` does not do reliably):
```bash
cd "$(git rev-parse --show-toplevel)"
buildroot/bin/mftest -t SKR_Pico -n1 -y # BTT SKR Pico, BOARD_BTT_SKR_PICO
```
`SKR_Pico` is the only RP2040 test folder under `buildroot/tests/` and is the canonical RP2040 target. The `ini/raspberrypi.ini` file also defines the `RP2040` and `RP2040-alt` environments (board `pico`), but they have no dedicated test folder, so `SKR_Pico` is what CI and maintainers build for this HAL.
> Build not verified in this environment — the Arduino-Pico / Raspberry Pi Pico SDK toolchain is not installed here. Run `mftest -t SKR_Pico -n1 -y` locally to confirm green. Do NOT use `rm -rf .pio/build/...` to force a rebuild — the cross-profile write guard blocks it and it is unsafe. Use `pio run -e SKR_Pico -t clean` (build artifacts only) or just let `mftest` rebuild.
## Framework / Platform Integration (upstream, not vendored)
The RP2040 Arduino core is **upstream**, NOT Marlin-vendored. It is the [Arduino-Pico core](https://arduino-pico.readthedocs.io/) (earlephilhower), which wraps the Raspberry Pi **Pico SDK** (`pico-sdk`) and TinyUSB. `ini/raspberrypi.ini` selects it:
- `env:RP2040` → `platform = raspberrypi`, `framework = arduino` (default `earlephilhower` core, board `pico`).
- `env:RP2040-alt` → `platform = https://github.com/maxgerhardt/platform-raspberrypi.git` with `board_build.core = earlephilhower`.
Because the framework is upstream, there is **no mirror-to-installed-package step** like AT32 requires. Marlin-specific glue lives entirely in `Marlin/src/HAL/RP2040/` (plus `buildroot/share/PlatformIO/` scripts common to all HALs). The compile guard is `-D__PLAT_RP2040__` (set in `raspberrypi.ini` `build_flags`), not `ARDUINO_ARCH_RP2040`. All HAL sources are guarded by `#ifdef __PLAT_RP2040__`.
### Gotchas that are not obvious from the source
1. **The MCU is dual-core and Marlin splits work across cores.** `MarlinHAL::adc_init()` launches `core1_adc_task()` on Core 1 via `multicore_launch_core1()` (`HAL.cpp`); it runs a continuous ADC scan loop forever. Marlin's `Temperature` ISR and main loop run on Core 0. Do not block or spin Core 1, and keep shared ADC state (`adc_values[]`, `*_heartbeat`) `volatile`. The watchdog refresh (`watchdog_refresh`) cross-checks both cores' heartbeats — if Core 1 stalls >2 s, Core 0 stops refreshing the WDT and lets the chip reset (`HAL.cpp`).
2. **`Serial` is USB-CDC, not a UART.** In the Arduino-Pico core, `Serial`/`SerialUSB` is the USB CDC ACM port and `Serial1`/`Serial2` are hardware UART0/UART1. Marlin's `MarlinSerial.h` wraps these as `MSerial0`/`MSerial1` (UART0/UART1) and `MSerial2` (USB). `SERIAL_PORT`/`SERIAL_PORT_2`/`LCD_SERIAL_PORT` are clamped to `-1..1` (`HAL.h`). USB-CDC emergency parsing requires `USBD_USE_CDC` + `EMERGENCY_PARSER` (`HAL.cpp`); otherwise Marlin talks over a real UART or the USB serial.
3. **EEPROM backend is per-board, not auto-selected.** The HAL ships two backends: `eeprom/eeprom_flash.cpp` (`FLASH_EEPROM_EMULATION`) and `eeprom/eeprom_wired.cpp` (`USE_WIRED_EEPROM`). Each RP2040 board's pins file must `#define` one of them; Marlin does not pick it automatically. The flash backend writes the **last flash sector** via `FLASH_TARGET_OFFSET = PICO_FLASH_SIZE_BYTES - FLASH_SECTOR_SIZE` and **assumes 2 MB flash** — change that if a board has different flash size (`eeprom_flash.cpp`). Writes disable interrupts around `flash_range_erase`/ `flash_range_program`.
4. **USB SD-host drive (MSC) is TinyUSB-based and off by default on RP2040.** `raspberrypi.ini` compiles with `-DNO_SD_HOST_DRIVE`; `HAS_SD_HOST_DRIVE` / `msc_sd.cpp` (TinyUSB `tud_msc_*_cb` callbacks) is only active if you drop that flag (see the commented `#custom_marlin.HAS_SD_HOST_DRIVE = tinyusb` line). The USB connect/disconnect toggle in `HAL.cpp` (`USB_CONNECT_PIN`) exists only when that pin is defined.
5. **`freeMemory()` relies on a linker symbol, not a stack probe.** It computes `(char*)&__StackLimit - (char*)_sbrk(0)` using the Pico linker-provided `__StackLimit` (`HAL.cpp`). Don't "fix" it with a local-variable subtraction as on single-stack chips — that is wrong on this core.
6. **`flashFirmware()` (M997) reboots into the bootloader via the watchdog.** `flashFirmware()` → `hal.reboot()` → `watchdog_reboot(0,0,1)` (`HAL.cpp`). The `raspberrypi.ini` build flags include `-DPLATFORM_M997_SUPPORT` (also forced on in `HAL.h`). A UF2/picotool upload picks up the reset.
7. **SPI uses the core's `<SPI.h>` directly; SOFTWARE_SPI path also exists.** `HAL_SPI.cpp` includes `<SPI.h>` and calls `spiBegin()`; a software-SPI fallback is compiled when `SOFTWARE_SPI` is enabled. There is no custom `SPI` global shim needed (unlike AT32). `spi_pins.h` pins live in `HAL/RP2040/`.
## Conventions
- All HAL source is guarded by `#ifdef __PLAT_RP2040__` (defined by `ini/raspberrypi.ini`, not by the core).
- Keep HAL changes in `Marlin/src/HAL/RP2040/` and board pin changes in `Marlin/src/pins/rp2040/`. Build/wrapper glue for the upstream core goes in `ini/raspberrypi.ini` + `buildroot/share/PlatformIO/` (no vendored framework to mirror).
- The framework is upstream Arduino-Pico (Pico SDK + TinyUSB): do not vendor or patch it in-repo for Marlin; if a core fix is needed, report upstream or keep it in the HAL.
- ADC is continuous on Core 1; temperature updates are driven from Core 0's `Temperature` ISR reading `adc_values[]`. Treat the ADC plumbing as a dual-core contract.
## Related
- `README.md` in this folder — overview and supported boards.
- Wiki: [[hal-rp2040]], [[marlin-src-hal]].
- `Marlin/src/HAL/shared/` — shared HAL APIs (`eeprom_api`, SPI helpers) the RP2040 HAL reuses.
- Upstream: <https://arduino-pico.readthedocs.io/en/latest/platformio.html>.

View file

@ -0,0 +1,56 @@
# AGENTS.md — SAMD21 HAL
Working notes and conventions for the **SAMD21 HAL** folder (`Marlin/src/HAL/SAMD21/`).
## Build & Test Loop
One real test target exists for this family. Validate with `mftest` (it regenerates `Marlin/Configuration.h` per target, which raw `pio run -e` does not do reliably):
```bash
cd "$(git rev-parse --show-toplevel)"
buildroot/bin/mftest -t SAMD21_minitronics20 -n1 -y # ReprapWorld Minitronics 2.0, SAMD21J18
```
`SAMD21_minitronics20` is the only SAMD21 env (`ini/samd21.ini`, `buildroot/tests/SAMD21_minitronics20/config-01.ini`, `motherboard = BOARD_MINITRONICS20`). It is the tightest (and only) constraint for SAMD21 — get it green and the family is covered. (The separate `SAMD51_grandcentral_m4` target is the SAMD51 family, not SAMD21 — do not confuse the two.)
The toolchain (`atmelsam` platform + upstream Arduino SAMD framework) is installed in this environment, so the build can actually be run here.
> Do NOT use `rm -rf .pio/build/...` to force a rebuild — the cross-profile write guard blocks it and it is unsafe. Use `pio run -e <env> -t clean` or just let `mftest` rebuild.
## Framework / Platform Integration (upstream, NOT vendored)
Unlike AT32, the SAMD21 Arduino core is the **upstream** PlatformIO `atmelsam` platform (`framework-arduino-samd-*`, e.g. `framework-arduino-samd-reprap`/`...-adafruit`) — there is no Marlin-vendored copy under `buildroot/share/PlatformIO/`. Marlin-specific glue lives in:
- `Marlin/src/HAL/SAMD21/` — the HAL itself (serial, SPI, ADC, timers, servo, EEPROM backends, u8g LCD drivers).
- `Marlin/src/pins/samd/` — board pin files (`pins_MINITRONICS20.h`, `pins_BRICOLEMON_V1_0.h`, `pins_BRICOLEMON_LITE_V1_0.h`, `pins_RAMPS_144.h`).
- `buildroot/share/PlatformIO/scripts/SAMD21_minitronics20.py` — per-env extra script (only adjusts `BUILD_FLAGS` serial buffer sizing).
Because the framework is upstream, there is **no mirror-to-installed-package warning** (that applies only to the vendored AT32 core).
### Gotchas that are not obvious from the source
1. **Compiler guard is `__SAMD21__`, set by build flags, not the core.** `HAL.h` / `HAL.cpp` / `HAL_SPI.cpp` / `eeprom_*.cpp` all key on `#ifdef __SAMD21__`, but the upstream Arduino SAMD core defines `ARDUINO_ARCH_SAMD`, not `__SAMD21__`. `ini/samd21.ini` passes `-D__SAMD21__`. **If you add a new SAMD21 board env, you MUST include `-D__SAMD21__` in its `build_flags` or nothing in this HAL compiles.**
2. **Primary serial is native USB-CDC, not a UART.** `HAL.h` defines `DefaultSerial1 = ForwardSerial1Class<SerialUSB>` as `MSerialUSB` and `#define USB_SERIAL_PORT(...) MSerialUSB`. Build flags add `-DUSBCON -DUSBD_USE_CDC` so `SerialUSB` exists. `Serial1`/`Serial2` map to hardware UARTs (`MSerial1`/`MSerial2` via SERCOM). The test config sets `serial_port = -1` for the UART and relies on USB — a board without native USB must re-point the serial port.
3. **Software SPI is a hard `#error`.** `HAL_SPI.cpp` rejects `SOFTWARE_SPI` / `FORCE_SOFT_SPI` ("Software SPI not supported for SAMD21. Use Hardware SPI."). `MarlinSPI` is just `SPIClass` (`MarlinSPI.h`), i.e. the upstream SAMD SERCOM SPI driver. `spiSendBlock()` _claims_ DMA in a comment but actually calls blocking `SPI.transfer()` — fine, just don't expect DMA offload on the SD path.
4. **EEPROM backend is per-board, not auto-selected.** `eeprom/` provides `I2C_EEPROM`, `FLASH_EEPROM_EMULATION`, and `QSPI_EEPROM` (the latter via `eeprom_qspi.cpp`/`QSPIFlash.cpp`), but `USE_WIRED_EEPROM` is an explicit `#error` ("Not implemented on SAMD21"). Each `pins/samd/*.h` must pick one: `BRICOLEMON_*` and `RAMPS_144` default to `I2C_EEPROM`; `MINITRONICS20` leaves `FLASH_EEPROM_EMULATION` commented out (with `MARLIN_EEPROM_SIZE 500U`). `QSPI_EEPROM` is coded but not selected by any current board.
5. **`WDT` macro collides with the CMSIS struct field.** In `HAL.cpp`, `get_reset_source()` wraps its body in `#pragma push_macro("WDT")` / `#undef WDT` / `#pragma pop_macro("WDT")` because `REG_WDT_CTRL` resolves to `.bit.WDT` and the preprocessor wrongly substitutes the `WDT` define. **Do not "fix" this by renaming the field — keep the macro push/pop.**
6. **ADC is free-running INPUTSCAN with remapped sensor order.** `adc_init()` configures the 12-bit ADC as 16-bit averaging (32 samples, DIV2 gain), free-running, scanning 3 contiguous AINs (`HAL_ADC_AIN_NUM_SENSORS = 3`). The SAMD21 ADC only scans contiguous AINs, so `ADC_Handler()` reads `RESULT` by `INPUTOFFSET` and `adc_start()` remaps the pin's AIN back to the array index (`HAL.cpp`). `HAL_ADC_FILTERED 1` means Marlin's own oversampling is disabled — the HAL already filters.
7. **48 MHz Cortex-M0+, no FPU.** SAMD21 tops out at 48 MHz with no hardware float unit; keep math in integer/fixed-point where hot. `freeMemory()` is a `_sbrk`/heap-end sbrk hack (`HAL.cpp`), not a real stack-check.
## Conventions
- All HAL source is guarded by `#ifdef __SAMD21__` — ensure new files and new board envs set `-D__SAMD21__` (see gotcha 1).
- Keep HAL changes in `Marlin/src/HAL/SAMD21/` and board pin changes in `Marlin/src/pins/samd/`. Build glue goes in `buildroot/share/PlatformIO/scripts/` (per-env) or `ini/samd21.ini`.
- Native USB CDC is the intended host link; treat `SerialUSB`/`MSerialUSB` as the primary port unless a board explicitly moves to a UART.
## Related
- `Marlin/src/pins/samd/` — board pin files (no `README.md` in the HAL folder).
- Wiki: [[hal-samd21]], [[marlin-src-hal]].
- `Marlin/src/HAL/shared/` — shared HAL APIs (`eeprom_api`, SPI helpers) the SAMD21 HAL reuses.

View file

@ -0,0 +1,51 @@
# AGENTS.md — SAMD51 HAL
Working notes and conventions for the **SAMD51 HAL** folder (`Marlin/src/HAL/SAMD51/`).
## Build & Test Loop
Validate with `mftest` (it regenerates `Marlin/Configuration.h` per target, which raw `pio run -e` does not do reliably):
```bash
cd "$(git rev-parse --show-toplevel)"
buildroot/bin/mftest -t SAMD51_grandcentral_m4 -n1 -y
```
There is exactly one SAMD51 test target: `SAMD51_grandcentral_m4`, which builds the Adafruit Grand Central M4 (`board = adafruit_grandcentral_m4`, `platform = atmelsam`) against `buildroot/tests/SAMD51_grandcentral_m4/config-01.ini` (board `BOARD_AGCM4_RAMPS_144`, TMC2209 + BLTouch + SD + EEPROM features). It must be green before considering SAMD51 work done. The Grand Central M4 has 1 MB flash / 256 KB RAM — not a tight flash constraint, but the build is the only real SAMD51 gate.
> Do NOT use `rm -rf .pio/build/...` to force a rebuild — it is unsafe and guarded. Use `pio run -e SAMD51_grandcentral_m4 -t clean` or just let `mftest` rebuild.
## Framework / Platform Integration (upstream, NOT vendored)
SAMD51 uses the **upstream Arduino SAMD core** (`atmelsam` platform + `framework-arduino-samd-*`), not a Marlin-vendored core like AT32. Do NOT mirror framework changes to a repo path — there is no `buildroot/share/PlatformIO/framework-*` for SAMD51; Marlin-specific glue lives only in `Marlin/src/HAL/SAMD51/` and the per-env build script.
- The `env:SAMD51_grandcentral_m4` section lives in `ini/samd51.ini`. It pulls in `Adafruit TinyUSB Library` and `SoftwareSerialM` as `lib_deps`, and adds `-DUSE_TINYUSB`.
- Marlin-specific build glue is in `buildroot/share/PlatformIO/scripts/SAMD51_grandcentral_m4.py`: it sets `-DSERIAL_BUFFER_SIZE` to `max(RX,TX,350)` from the resolved config. If you change how serial buffers are sized, update this script.
- EEPROM backend is **per-board, not auto-selected**. The HAL ships three backends that compile only when explicitly enabled: `eeprom/eeprom_wired.cpp` (`USE_WIRED_EEPROM`, needs `MARLIN_EEPROM_SIZE`), `eeprom/eeprom_qspi.cpp` (`QSPI_EEPROM`, via `QSPIFlash`), and `eeprom/eeprom_flash.cpp` (`FLASH_EEPROM_EMULATION`, SAMD51 NVM smart-EEPROM). Each SAMD51 board's pins file must `#define` the one it uses (`pins_RAMPS_144.h` / `pins_BRICOLEMON*.h` set these). Marlin does NOT auto-pick one.
### Gotchas that are not obvious from the source
1. **Native USB via TinyUSB, not Serial.** The Grand Central M4 exposes native USB CDC through Adafruit TinyUSB (`-DUSE_TINYUSB`). The USB serial is `Serial` (a `Serial_`, i.e. USB CDC), while hardware UARTs are `Serial1`/`Serial2`/… Marlin's port mapping in `MarlinSerial_AGCM4.h` aliases `MSerial0` → `Serial` (USB) and `MSerial1..4` → `Serial1..4`. `USB_SERIAL_PORT(...)` is `MSerial0`. If a board has no USB-CDC `Serial`, `USING_HW_SERIALUSB` is false and `MSerial0` is not defined — guard any USB-only code behind that macro (see `HAL.cpp:33`).
2. **Extra UARTs are defined by the HAL, not the framework.** The Adafruit core leaves `Serial2`–`Serial4` undefined to save SERCOM resources. `MarlinSerial_AGCM4.cpp` instantiates them on specific SERCOMs (`Serial2`→SERCOM4, `Serial3`→SERCOM1, `Serial4`→SERCOM5) and provides the matching `SERCOMx_y_Handler()` ISRs. If you add a hardware serial port, you must wire both the `UartT` instance and its four SERCOM interrupt handlers here, or it will silently not receive data.
3. **Pin representation is an integer Arduino index, not an enum.** `pin_t` is `int8_t` and `GET_PIN_MAP_PIN(index)`/`GET_PIN_MAP_INDEX(pin)` are identity, so `PIN_EXISTS(P)` works in the preprocessor (no AT32-style enum-pin trap). The SAMD port/pin is derived later via `SAMD51.h` macros (`PIN_TO_SAMD_PIN` → `DIO##P##_PIN` from the framework's `pins_arduino.h`). Don't reintroduce an enum-based pin scheme.
4. **ADC uses both ADC0 and ADC1 behind a DMA scan.** `HAL.cpp` builds an `ADCIndex` enum and a `PIN_TO_INPUTCTRL` list split into ADC0-then-ADC1 inputs, then drives conversion via `Adafruit_ZeroDMA` (`DMA_IS_REQUIRED` whenever any ADC is used). The `GET_TEMP_n_ADC()` / `GET_*_ADC()` macros must resolve to ADC unit 0 or 1; a pin mapped to the wrong ADC unit silently won't be sampled. Watchdog refresh must happen during long operations so the 4–8 s WDT (`WDT_CONFIG_PER_CYC*`) doesn't trip.
5. **Software SPI is unsupported.** `HAL_SPI.cpp` `#error`s on `SOFTWARE_SPI` / `FORCE_SOFT_SPI` — SAMD51 only does hardware SPI. SD SPI uses `SDCARD_SPI` when the SD is `ONBOARD` (QSPI), else the global `SPI`. `spiSendBlock()` uses DMA transfer. `MarlinSPI` is just `SPIClass` (`MarlinSPI.h`).
6. **SERCOM/SD/QSPI sharing.** The Grand Central M4 routes the SD card over QSPI (`sdcard_connection = LCD` maps to the onboard SPI/QSPI flash in the test config). Repurposing SERCOM or QSPI pins in a board's pins file can collide with the SD/QSPI backend — the board comments in `pins/samd/` warn to "be careful with the Sercom configurations" when enabling hardware serials.
## Conventions
- All HAL source is guarded by `#ifdef __SAMD51__` (the compiler macro for the SAM D51 family; `HAL/platforms.h` maps `__SAMD51__` → `HAL/SAMD51/`). Board-variant glue is further guarded by `#ifdef ADAFRUIT_GRAND_CENTRAL_M4`.
- Keep HAL changes in `Marlin/src/HAL/SAMD51/` and board pin changes in `Marlin/src/pins/samd/` (e.g. `pins_RAMPS_144.h`, `pins_BRICOLEMON*.h`). Build/env glue goes in `buildroot/share/PlatformIO/scripts/SAMD51_grandcentral_m4.py` and `ini/samd51.ini`.
- Because the framework is upstream, HAL fixes must be portable — don't assume a Marlin-patched core. Anything that needs a core change has to go through Adafruit's `framework-arduino-samd-adafruit` upstream.
## Related
- `README.md` — none in this folder yet.
- Wiki: [[hal-samd51]], [[marlin-src-hal]].
- `Marlin/src/HAL/shared/` — shared HAL APIs (`eeprom_api`, SPI helpers) the SAMD51 HAL reuses.
- `Marlin/src/pins/samd/` — SAMD51 board pin definitions.

View file

@ -0,0 +1,83 @@
# AGENTS.md — STM32 HAL
Working notes and conventions for the **STM32 HAL** folder (`Marlin/src/HAL/STM32/`).
The STM32 HAL covers the **official STM32duino** ("generic STM32") core and serves the entire STM32 F0 / F1 / F4 / F7 / G0 / H7 family (and friends) from one directory. It is the primary 32-bit target for Marlin.
## Build & Test Loop
Always validate with `mftest` (it regenerates `Marlin/Configuration.h` per target, which raw `pio run -e` does not do reliably):
```bash
cd "$(git rev-parse --show-toplevel)"
buildroot/bin/mftest -t STM32F103RE -n1 -y # STM32F103RE, generic variant (F1)
buildroot/bin/mftest -t STM32F103RC_btt -n1 -y # SKR Mini E3 (F103RC, variant)
buildroot/bin/mftest -t STM32F401RC_creality -n1 -y # Creality F401RC (F4)
buildroot/bin/mftest -t STM32F446VE_fysetc -n1 -y # FYSETC S6 / Spider (F446)
buildroot/bin/mftest -t STM32F407VE_black -n1 -y # "Black" F407VET6 (F4)
buildroot/bin/mftest -t NUCLEO_F767ZI -n1 -y # Nucleo F767ZI (F7)
buildroot/bin/mftest -t STM32G0B1RE_btt -n1 -y # BIGTREETECH G0B1RE (G0)
buildroot/bin/mftest -t STM32H743VI_btt -n1 -y # BIGTREETECH H743VI (H7)
```
Targets should be picked to span the families (F1 / F4 / F7 / G0 / H7) and both the `common_stm32` and `stm32_variant` code paths. The F103 generic (`STM32F103RE`) and an F4 board (`STM32F446VE_fysetc`) are the cheapest, highest-value smoke tests; the H7 build (`STM32H743VI_btt`) exercises the 32-bit-timer / FMC-TFT paths not seen elsewhere.
> Do NOT use `rm -rf .pio/build/...` to force a rebuild — the cross-profile write guard blocks it and it is unsafe. Use `pio run -e <env> -t clean` (removes only build artifacts) or just let `mftest` rebuild.
### Maple legacy path is a SEPARATE HAL
`*_maple` boards (e.g. `chitu_f103`, `mks_robin_maple`, `jgaurora_a5s_a1_maple`, `STM32F103RC_btt_maple`, `STM32F103RC_fysetc_maple`) do **not** use this folder. They compile against the legacy **LibMaple** core via `ini/stm32f1-maple.ini`, which sets `board_build.core = maple` and `-DMAPLE_STM32F1`, and pull sources from `src/HAL/STM32F1/` (a distinct HAL). If a maple board fails, the fix usually lives in `HAL/STM32F1/`, not here. Treat maple as out-of-scope for changes to `HAL/STM32/`.
## Framework / Platform Integration (upstream, NOT vendored)
Unlike the AT32 HAL, the STM32 HAL uses the **upstream STM32duino framework**, pulled from the PlatformIO registry — it is **not** vendored under `buildroot/share/PlatformIO/`.
- Platform: `platform = ststm32@~12.1` (STM32 commons in `ini/stm32-common.ini`).
- Core / framework: `board_build.core = stm32` → the official `framework-arduinoststm32` (Arduino_Core_STM32) package installed by PlatformIO into `~/.platformio/packages/`.
- The **USB Flash Drive** mix-in (`[stm_flash_drive]`) is the one exception: it points `framework-arduinoststm32` at MarlinFirmware's fork archive (`Arduino_Core_STM32/archive/stm-flash-drive.zip`).
Consequences:
- Framework/toolchain fixes belong **upstream** (the installed PlatformIO package), not in the Marlin repo. There is no vendored copy to keep in sync — do not go looking for one.
- All STM32 `mftest` targets therefore require the `ststm32` platform + STM32duino core to already be installed in the PlatformIO cache. If a build fails with "unknown package / platform ststm32", run a normal `pio` install rather than editing repo files.
- `HAL_STM32` is the guard macro set by the build (`-DHAL_STM32` in `common_stm32`), not `ARDUINO_ARCH_STM32` alone. HAL sources guard on `#ifdef HAL_STM32`. (The maple path instead defines `ARDUINO_ARCH_STM32 -DMAPLE_STM32F1`.)
### Gotchas that are not obvious from the source
1. **`Serial` vs `MSerial1` — there is no bare `Serial`.** The Arduino STM32 core defines `Serial1`…`SerialN`, not a default `Serial`. Marlin's `MarlinSerial.h` wraps them as `MSerial1`…`MSerial10` (`Serial1Class<MarlinSerial>`) and the shared `serial_ports.h` maps `Serial` to `MSerial1` only when a port index 0 is selected. **Do not reference the bare `Serial` object in HAL code** expecting the Arduino default — use `MSerialN` or the configured `SERIAL_PORT` index. When `USBCON` is set, `SerialUSB` is wrapped as `MSerialUSB` and `USB_SERIAL_PORT(...)` resolves to it.
2. **USB-CDC vs hardware UART is a build-flag split, not a code split.** `common_stm32` builds with `-DUSBCON -DUSBD_USE_CDC` (USB CDC is the _default_ serial transport). Many boards `build_unflags` those and set `DISABLE_GENERIC_SERIALUSB` to fall back to a real UART (e.g. `rumba32`, `Anet_ET4`, the `lerdge_*` family) and enable `-DHAL_UART_MODULE_ENABLED`. So "is the port USB or UART?" is decided entirely by `build_flags`/`build_unflags`, not by which `Serial` object you touch. Watch for `-DUSE_USB_FS`, `-DUSBD_USE_CDC_MSC`, `-DUSBD_USE_CDC_COMPOSITE` variants too.
3. **EEPROM backend is per-board, not auto-selected.** Marlin does NOT auto-pick an EEPROM backend on STM32. Each board must `#define` one of `FLASH_EEPROM_EMULATION`, `SDCARD_EEPROM_EMULATION`, `IIC_EEPROM`, `SPI_EEPROM`, `SRAM_EEPROM`, etc. in its pins/Configuration files. The `eeprom/` subfolder ships ALL of these backends (`eeprom_flash.cpp`, `eeprom_sdcard.cpp`, `eeprom_if_iic.cpp`, `eeprom_bl24cxx.cpp`, `eeprom_sram.cpp`, …) but only the one selected is compiled. `FLASH_EEPROM_EMULATION` (via the core `EEPROM.h`) works only on parts with a single "sector" flash design; `FLASH_EEPROM_LEVELING` is hard-guarded to `STM32F4xx`/`STM32H7xx` only (see `inc/SanityCheck.h`). Do not assume flash-emulation works on an F0/F1/G0.
4. **Pins must be `#define` macros, or SanityCheck dies.** `inc/SanityCheck.h` opens with `#ifndef PA0 #error "Your ARM platform pins are not defined as macros, only as enums!"`. The STM32duino core represents pins as `PinName` enums, so each board/variant supplies a `pins_arduino.h` (or the generated variant) that re-exposes `PA0`, `PC6`, … as numeric `#define`s. If you add a board and hit that `#error`, the fix is at the pin-define level — **not** by relaxing SanityCheck. (`HAL.h` uses `typedef int32_t pin_t;` for parity with `platform/ststm32`.)
5. **FastIO needs `FastIO_init()` before use.** `fastio.h` routes `_WRITE`/`_READ`/`_TOGGLE` through `FastIOPortMap[]` and requires `FASTIO_INIT()` (`FastIO_init()`) to be called first; otherwise the port table is unpopulated. The F0/F1/L0/L4 branch uses `BRR` while F2/F4/F7/H7 use the `BSRR` high/low-bit form — a subtle per-family macro split.
6. **Timers are 16- or 32-bit per part.** `timers.h` defines `hal_timer_t uint32_t` but comments that STM32F0 pauses timers if `UINT32_MAX` is written to a 16-bit counter register; the 32-bit capability is queried at runtime via `IS_TIM_32B_COUNTER_INSTANCE`. Servo, stepper, and temperature timing all depend on `TIMER_SERIAL`/`TIMER_SERVO` being assigned a valid timer (e.g. `-DTIMER_SERIAL=TIM9`), and ISR priorities are pinned (`-DTIM_IRQ_PRIO=13`, USB host `USBH_IRQ_PRIO=3`). Changing a timer without rechecking the priority map can deadlock serial ISRs.
7. **ADC resolution is forced to 12-bit.** `HAL.h` sets `HAL_ADC_RESOLUTION 12` (or `ADC_RESOLUTION` if defined; `common_stm32` passes `-DADC_RESOLUTION=12`), and `MarlinHAL::adc_init()` calls `analogReadResolution(HAL_ADC_RESOLUTION)`. Don't hardcode a 10-bit assumption in sensor code.
8. **SPI is wrapped, not the raw core class.** `MarlinSPI.h` wraps the STM32duino `SPIClass` (via `utility/spi_com.h`) and exposes the `SPIClass`/`SPISettings` globals libraries expect (`HAL/shared/HAL_SPI.h`). `spi_pins.h` selects AF pins. Touching SPI for TFT/LCD or card readers goes through this wrapper, not a bare `SPI.begin()`.
9. **Servo uses `libServo` over the core `Servo`.** `Servo.h` defines `libServo` as a subclass of the STM32duino `Servo`, with `pause_all_servos()`/`resume_all_servos()` (referenced from `HAL.h` as `PAUSE_SERVO_OUTPUT`/`RESUME_SERVO_OUTPUT`) and an interrupt-priority setter. Use `libServo`, not the raw core `Servo`, in HAL-adjacent code.
10. **TFT backends are conditionally compiled in.** `common_stm32` excludes `src/HAL/STM32/tft` by default and re-adds only the pieces a board needs via `custom_marlin.*` switches (`HAS_LTDC_TFT`, `HAS_FSMC_TFT`, `HAS_SPI_TFT`, `HAS_TFT_XPT2046`, `TFT_TOUCH_DEVICE_GT911`). FSMC needs `-DHAL_SRAM_MODULE_ENABLED`. Don't add a `#include` of a tft cpp expecting it to always be linked — it may be filtered out of the build.
11. **`M997` firmware flash / reboot is supported.** `HAL.h` defines `PLATFORM_M997_SUPPORT` and `flashFirmware()`; STM32 can apply firmware updates in place (bootloader-dependent). The maple F1 path is the one notable case that uses a different core entirely (see above).
## Conventions
- All HAL source is guarded by `#ifdef HAL_STM32` (set by `common_stm32`'s `-DHAL_STM32`). Do not key STM32-specific code on `ARDUINO_ARCH_STM32` alone, since the maple legacy path also defines that.
- Keep HAL changes in `Marlin/src/HAL/STM32/` and board pin changes in `Marlin/src/pins/stm32f1/` (and the other `pins/` families). Variant `pins_arduino.h` files for `stm32_variant` boards are auto-generated by `buildroot/share/PlatformIO/scripts/generic_create_variant.py` — edit the source pins file, not the generated variant.
- PlatformIO integration lives in `ini/stm32-common.ini` (`[common_stm32]`, `[stm32_variant]`, `[stm_flash_drive]`) and the per-family `ini/stm32f*.ini`; framework behavior is upstream (STM32duino), not vendored — there is no repo copy to mirror.
- When changing serial/USB behavior, remember the upstream-framework + `build_flags` split (gotcha #2): the fix is usually a flag in the board env or a variant define, not HAL C++.
- Pin mappings must remain as numeric `#define`s (gotcha #4). Mark any placeholder pins as such and don't "fix" them to guesses without a source.
## Related
- `README.md` in this folder — overview and supported STM32 families.
- Wiki: [[hal-stm32]], [[marlin-src-hal]].
- `Marlin/src/HAL/shared/` — shared HAL APIs (`eeprom_api`, `serial_ports.h`, `HAL_SPI.h`) the STM32 HAL reuses.
- `Marlin/src/HAL/STM32F1/` — the **legacy LibMaple** HAL for `*_maple` boards (separate core, out of scope for this folder).
- `Marlin/src/pins/stm32f1/` and sibling `pins/` families — board pin tables.

View file

@ -0,0 +1,72 @@
# AGENTS.md — STM32F1 HAL
Working notes and conventions for the **STM32F1 HAL** folder (`Marlin/src/HAL/STM32F1/`).
This HAL targets STM32F103 (and GD32F103 / N32G455 clones) boards using the **LibMaple-based** "Roger Clark" Arduino_STM32 core (`board_build.core = maple`), NOT the unified STM32duino core that the rest of the STM32 family uses.
## Build & Test Loop
Always validate with `mftest` (it regenerates `Marlin/Configuration.h` per target):
```bash
cd "$(git rev-parse --show-toplevel)"
buildroot/bin/mftest -t STM32F103RC_btt_maple -n1 -y # SKR Mini E3 1.0, 256K
buildroot/bin/mftest -t mks_robin_maple -n1 -y # MKS Robin, FSMC UI
buildroot/bin/mftest -t jgaurora_a5s_a1_maple -n1 -y # JGAurora A5S/A1, ZE
buildroot/bin/mftest -t STM32F103RC_meeb_maple -n1 -y # MEEB_3DP, 512K, USB
buildroot/bin/mftest -t mks_robin_nano_v1v2_maple -n1 -y # Robin Nano, FSMC
buildroot/bin/mftest -t STM32F103VE_longer_maple -n1 -y # Alfawise U20, VE
buildroot/bin/mftest -t mks_robin_pro_maple -n1 -y
buildroot/bin/mftest -t mks_robin_lite_maple -n1 -y
buildroot/bin/mftest -t STM32F103RC_fysetc_maple -n1 -y
buildroot/bin/mftest -t STM32F103RC_btt_USB_maple -n1 -y # USB Composite
buildroot/bin/mftest -t STM32F103VE_ZM3E4V2_USB_maple -n1 -y
```
> **Only the `_maple` envs in `ini/stm32f1-maple.ini` compile this HAL** (`build_src_filter` includes `src/HAL/STM32F1`, `-DMAPLE_STM32F1`). The non-maple envs in `ini/stm32f1.ini` (`STM32F103RE`, `mks_robin`, `STM32F103RE_creality`, …) extend `common_stm32` and build the **unified** `src/HAL/STM32` (`-DHAL_STM32`) — they do NOT exercise this folder.
> Do NOT use `rm -rf .pio/build/...` to force a rebuild — the cross-profile write guard blocks it and it is unsafe. Use `pio run -e <env> -t clean` or just let `mftest` rebuild.
## Framework / Platform Integration (upstream, not vendored)
The STM32F1 (LibMaple) core is pulled from the **upstream** `ststm32@~15.4.1` PlatformIO platform (`board_build.core = maple`) — it is **not** vendored by Marlin, so there is no "mirror to installed package" step (that warning is AT32-specific only). Marlin-specific glue lives in:
- `Marlin/src/HAL/STM32F1/` — the HAL itself.
- `buildroot/share/PlatformIO/scripts/STM32F1_build_flags.py` — emits base C/CXX/LINK flags (`-Os`, `-mcpu=cortex-m3`, `-ffreestanding`, `--specs=nano.specs`, `-IMarlin/src/HAL/STM32F1`, `-DTARGET_STM32F1 -DARDUINO_ARCH_STM32 -DPLATFORM_M997_SUPPORT`).
- `buildroot/share/PlatformIO/scripts/{fix_framework_weakness,stm32_serialbuffer,custom_board,offset_and_rename,STM32F1_create_variant}.py` — run as `pre:`/`custom_marlin` extras (per-board offsets, variant creation for Chitu/Meeb).
Toolchain is pinned: `toolchain-gccarmnoneeabi@1.120301.0` (else GCC 7.2.1) and `tool-stm32duino`. `lib_ignore = SPI, FreeRTOS701, FreeRTOS821`; `SoftwareSerialM` is added.
### Gotchas that are not obvious from the source
1. **Two different "STM32F1" paths.** `ini/stm32f1.ini` targets (e.g. `STM32F103RE`, `mks_robin`) silently use the unified `HAL/STM32`, while only `ini/stm32f1-maple.ini` targets use this `HAL/STM32F1`. Changing one does not test the other — build a `_maple` target to exercise this folder.
2. **Pins are numeric `#define`s, not an `enum`.** `fastio.h` defines `PA0 0x00` … `PG15 0x6F` and macros use the libmaple `PIN_MAP[IO]` table (e.g. `READ`/`WRITE`). Unlike the AT32 `enum` quirk, `PIN_EXISTS` works in the preprocessor here. BUT the **CB/C8 parts** only expose `PC13/PC14/PC15` (guarded at `fastio.h:97`), while larger parts expose `PC0‑PC15` — pin files must match the die.
3. **Flash size / linker script are per-board.** `HAL.h` defaults `STM32_FLASH_SIZE` to 256, but 512 for `MCU_STM32F103RE/VE/ZE`. Each env passes its own `board_build.ldscript` (`creality256k.ld`, `creality.ld`, `crealityPro.ld`, `mks_robin.ld`, `mks_robin_mini.ld`, `fly_mini.ld`, `jgaurora_a5s_a1.ld`, `ZONESTAR_ZM3E_*.ld`, …). Mismatched `.ld` → silent overflow or wrong vector table.
4. **EEPROM backend is auto-fallback, not auto-selected.** `inc/Conditionals_post.h` defines `SDCARD_EEPROM_EMULATION` only when `USE_FALLBACK_EEPROM` (no I2C/SPI/flash EEPROM). `eeprom/` carries `eeprom_sdcard`, `eeprom_wired`, `eeprom_if_iic`, `eeprom_flash`, `eeprom_bl24cxx` — a board pins file must pick one. `SDCARD_EEPROM_EMULATION` requires `SDSUPPORT` (else `SanityCheck.h` warns and undefs it).
5. **N32 (Nationstar) clone layer.** `HAL_N32.h/.cpp` re-implements ADC/GPIO/DMA register maps for the N32G455 (board `N32G455RE_voxelab_maple`, `-DVOXELAB_N32`). It is not a generic N32 port — don't assume other N32 parts build.
6. **USB vs hardware UART.** Default is hardware USART (`HardwareSerial`). USB serial is opt-in: `MarlinSerial.h` only defines `USBSerial`/`UsbSerial` under `#ifdef SERIAL_USB`, and the Zonestar/Meeb/BTT-USB targets add `USBComposite for STM32F1` + `-DUSE_USB_COMPOSITE` / `-DSERIAL_USB`. Don't enable USB flags on a UART-only board.
7. **Timer assignments vary per board.** `TIMER_SERVO`, `TIMER_TONE`, `SS_TIMER`, `TEMP_TIMER_CHAN` are set in each env (e.g. `TIMER_SERVO=TIM5`, `SS_TIMER=4`). Two Chitu envs expose `chitu_v5_gpio_init` / `-DCHITU_V5_Z_MIN_BUGFIX` for a known GPIO-init bug (use when G28/G29 always fail on Chitu V5).
8. **GD32F103 / N32 reuse this HAL.** `GD32F103RC_voxelab_maple`, `N32G455RE_voxelab_maple`, and `STM32_XL_DENSITY` Z-parts (`jgaurora_a5s_a1_maple`, `chitu_f103_maple`) all build `src/HAL/STM32F1`, so a HAL change can affect clone boards too.
9. **`SPI` global.** The maple core leaves `SPI` out; `HAL_SPI.cpp` instantiates `SPIClass SPI(...)` and provides `spiBegin()` (mirrors the AT32 pattern).
## Conventions
- Source is selected by the `MAPLE_STM32F1` build flag (with `ARDUINO_ARCH_STM32`); some files guard on `BOARD_NR_GPIO_PINS` ("Only in MAPLE_STM32F1", see `pinsDebug.h`).
- Keep HAL changes in `Marlin/src/HAL/STM32F1/` and board pin changes in `Marlin/src/pins/stm32f1/` (and the various `pins/` clones). Build/glue changes go in `buildroot/share/PlatformIO/scripts/` and `ini/stm32f1-maple.ini`.
- Build flags live in `STM32F1_build_flags.py` (a `pre:` extra), **not** in `platform.json`.
- Pin tables in `fastio.h` are MCU-die-specific (CB/C8 vs others) — don't generalize.
## Related
- `README.md` in this folder — overview and supported boards.
- Wiki: [[hal-stm32f1]], [[marlin-src-hal]].
- `Marlin/src/HAL/shared/` — shared HAL APIs (`eeprom_api`, SPI helpers) this HAL reuses.
- `Marlin/src/HAL/STM32/` — the unified STM32duino HAL that the non-maple F1 targets use.

View file

@ -0,0 +1,51 @@
# AGENTS.md — TEENSY31_32 HAL
Working notes and conventions for the **TEENSY31_32 HAL** folder (`Marlin/src/HAL/TEENSY31_32/`). This HAL drives the PJRC Teensy 3.1 / 3.2 boards (NXP/Freescale MK20DX256, ARM Cortex-M4, 72 MHz, 256 KB flash). **Unlike AT32, the Teensy core is NOT vendored** — it is the upstream Teensyduino/Arduino core pulled in by the `teensy` PlatformIO platform.
## Build & Test Loop
Validate with `mftest` (it regenerates `Marlin/Configuration.h` per target, which raw `pio run -e` does not do reliably):
```bash
cd "$(git rev-parse --show-toplevel)"
buildroot/bin/mftest -t teensy31 -n1 -y # BOARD_TEENSY31_32, MK20DX256
```
`buildroot/tests/teensy31/` holds three configs (`config-01` default, `config-02` zero-endstops, `config-03` many-features). They all target the same board (`BOARD_TEENSY31_32`); `config-03` is the tightest constraint — the full-feature build that stresses the 256 KB flash. All three must be green before considering Teensy 3.1/3.2 work done.
> Do NOT use `rm -rf .pio/build/...` to force a rebuild — the cross-profile write guard blocks it and it is unsafe. Use `pio run -e teensy31 -t clean` (removes only build artifacts) or just let `mftest` rebuild.
## Framework / Platform Integration (upstream, not vendored)
The Teensy Arduino core is the **upstream** Teensyduino package (`framework-arduinoteensy`, platform `teensy@~4.12.0` in `ini/teensy.ini`), installed at `~/.platformio/packages/framework-arduinoteensy*`. It is NOT vendored under `buildroot/share/PlatformIO/` (that is the AT32 exception). There is no "mirror to the installed package" step — changes to Marlin glue live only in this HAL folder, and the core comes straight from the PlatformIO registry.
- `ini/teensy.ini` `[env:teensy31]` extends `teensy_arm` with `board = teensy31` and adds `src/HAL/TEENSY31_32` to `build_src_filter`. When you add a new HAL source file it is picked up automatically by that filter.
- EEPROM backend: this HAL uses the **wired** EEPROM (`<avr/eeprom.h>`) — the MK20DX256 has 2 KB of real EEPROM. No per-board `SDCARD_EEPROM_EMULATION` / `I2C_EEPROM` / `FLASH_EEPROM` define is needed; `eeprom.cpp` builds under `USE_WIRED_EEPROM`.
### Gotchas that are not obvious from the source
1. **The compiler guard is `__MK20DX256__`, not `ARDUINO_ARCH_TEENSY`.** Every `.cpp` in this folder is wrapped in `#ifdef __MK20DX256__`, and `platforms.h` maps that macro to `HAL/TEENSY31_32`. The Teensy 3.5/3.6 and 4.0/4.1 HALs all share the `teensy_arm` platform/`teensy` toolchain, so a missing guard would compile your file for the wrong MCU. Always keep the `#ifdef __MK20DX256__` guard.
2. **EEPROM is wired `<avr/eeprom.h>`, not SD/flash emulation.** `eeprom.cpp` calls the AVR-style `eeprom_read_byte`/`eeprom_write_byte` against `REAL_EEPROM_ADDR(pos)` and is gated on `USE_WIRED_EEPROM`. Do NOT add `SDCARD_EEPROM_EMULATION` or any SPI/I2C backend — the silicon has real EEPROM.
3. **Bus-clock hard assumption in `timers.cpp`.** `HAL_timer_start()` derives FTM compare values from `FTM0_TIMER_RATE`/`FTM1_TIMER_RATE` presuming a **60 MHz bus clock**. The `teensy31` board JSON sets `F_CPU` accordingly; if that ever changes the step/temp timers run at the wrong rate. Also note `adc_init()` calls `NVIC_ENABLE_IRQ(IRQ_FTM1)` — the temperature timer (FTM1) must be enabled there for the shared temperature ISR to fire.
4. **SPI wraps the Teensyduino `SPI` library, not a custom driver.** `HAL_SPI.cpp` calls `SPI.begin()` / `SPI.transfer()` from upstream `<SPI.h>`; `MarlinSPI` is just `SPIClass`. `spiSendBlock()` still contains dead AVR `SPDR`/`SPSR` register code — that path is disabled; the active path uses `SPI.transfer`. Don't be misled into "fixing" it as a register driver.
5. **Servo `move()` calls `attach(0)` — the `0` is a placeholder, not pin 0.** `Servo.cpp` stores the real pin in `servoPin[servoIndex]` and `libServo::move()` re-attaches with `attach(0)`, which resolves to the stored entry. Do NOT change it to the actual pin number.
6. **ADC reads go through a fixed `pin2sc1a[]` lookup, not `analogRead`.** `adc_start()` indexes a hand-built table (`HAL.cpp`) that maps Marlin pin numbers to MK20DX256 SC1A ADC channels. The `analogInputToDigitalPin` macro in `HAL.h` only covers the first 12 A pins. Route analog sampling through `hal.adc_start()`/`adc_value()`, never `analogRead()`.
## Conventions
- All HAL source is guarded by `#ifdef __MK20DX256__` (plus `IS_TEENSY31_32` / `IS_TEENSY32` in `HAL.h`). The upstream framework also defines `ARDUINO_ARCH_TEENSY`, but the HAL does not rely on it for selection.
- Keep HAL changes in `Marlin/src/HAL/TEENSY31_32/` and board pin changes in `Marlin/src/pins/teensy3/pins_TEENSY31_32.h`. Core/PlatformIO integration is upstream — there is no vendored framework to edit here.
- `fastio.h` header comment says "Teensy 3.5 and 3.6" but is the 3.1/3.2 implementation; it uses Cortex-M bitbanding via the core's `CORE_PINxx_PORTSET`/`PORTCLEAR` symbols. Note `_IS_OUTPUT` is defined identically to `_IS_INPUT` — output direction is not actually distinguished; harmless today, but avoid adding output-direction checks that depend on it.
- Serial: `Serial0` aliases the core `Serial`; `USBSerial` wraps `SerialUSB`; multi-port `DefaultSerialX` objects forward to `SerialX`. `SERIAL_INDEX_MIN/MAX` is 0..3.
## Related
- Wiki: [[hal-teensy31-32]], [[marlin-src-hal]].
- `Marlin/src/HAL/shared/` — shared HAL APIs (`eeprom_api`, SPI helpers) this HAL reuses.
- `Marlin/src/pins/teensy3/pins_TEENSY31_32.h` — board pin map.
- `ini/teensy.ini` — `[env:teensy31]` build definition.

View file

@ -0,0 +1,57 @@
# AGENTS.md — TEENSY35_36 HAL
Working notes and conventions for the **TEENSY35_36 HAL** folder (`Marlin/src/HAL/TEENSY35_36/`).
Targets PJRC **Teensy 3.5** (MK64FX512, 512 KB flash) and **Teensy 3.6** (MK66FX1M0, 1 MB flash) — both ARM Cortex-M4. They share this one HAL folder; the physical chip is selected by the compiler macro `__MK64FX512__` / `__MK66FX1M0__` (set by the PlatformIO `teensy35` / `teensy36` board JSONs), not by a runtime check.
## Build & Test Loop
Validate with `mftest` (it regenerates `Marlin/Configuration.h` per target, which raw `pio run -e` does not do reliably):
```bash
cd "$(git rev-parse --show-toplevel)"
buildroot/bin/mftest -t teensy35 -n1 -y # Teensy 3.5 (MK64FX512)
buildroot/bin/mftest -t teensy35 -n8 -y # ...dual-Z endstop stress config
```
All real test targets for this HAL live under `buildroot/tests/teensy35/` (`config-01` … `config-08`, all with `motherboard = BOARD_TEENSY35_36`). There is no `buildroot/tests/teensy36/` folder — the 3.6 build reuses the same HAL and board define, only differing by the PlatformIO `board = teensy36` (which flips `__MK66FX1M0__` on). To exercise the 3.6-only path, build env `teensy36` (`pio run -e teensy36`); otherwise the `teensy35` targets cover the shared code.
The tighter constraint is the **Teensy 3.5** (512 KB flash). If it fits there, the 3.6 (1 MB) will too.
> Do NOT use `rm -rf .pio/build/...` to force a rebuild — the cross-profile write guard blocks it and it is unsafe. Use `pio run -e <env> -t clean` (removes only build artifacts) or just let `mftest` rebuild.
## Framework / Platform Integration (upstream, NOT vendored)
The Teensy Arduino core is the **upstream Teensyduino** package (`platform = teensy@~4.12.0` in `ini/teensy.ini`), provided by PlatformIO — it is NOT vendored under `buildroot/share/PlatformIO/` like the AT32 framework is. The `teensy_arm` env pulls in Teensyduino's `cores/teensy3/` (register headers like `kinetis.h`, `pins_teensy.h`, and the native `Serial1…`, `SerialUSB`, `SPI`, `Wire`, and `avr/eeprom.h` emulation). Marlin glue lives entirely in this HAL folder plus `Marlin/src/pins/teensy3/pins_TEENSY35_36.h`.
There is no installed-package-vs-repo mirror step (that warning applies only to the vendored AT32 framework). Build changes are just source edits under `Marlin/src/HAL/TEENSY35_36/` and `buildroot/` scripts.
### Gotchas that are not obvious from the source
1. **Chip is chosen by a compile-time macro, not runtime.** `HAL.h` does `#ifdef __MK66FX1M0__ … IS_TEENSY36 … #else IS_TEENSY35`, and every `.cpp` in the folder is wrapped in `#if defined(__MK64FX512__) || defined(__MK66FX1M0__)`. The 3.5 vs 3.6 distinction comes purely from the `board = teensy35` / `board = teensy36` PlatformIO JSON. Don't add runtime branching for the chip.
2. **No real EEPROM — the core emulates it in flash.** `eeprom.cpp` uses `USE_WIRED_EEPROM` and `#include <avr/eeprom.h>`; Teensyduino supplies an _emulated_ EEPROM (backed by program flash) since the Kinetis parts have no physical EEPROM. `MARLIN_EEPROM_SIZE` defaults to `E2END + 1`. The HAL adds `delay(2)` / `safe_delay(2)` between byte writes specifically to avoid tripping the watchdog during the slow flash-write cycles — keep that; it is load-bearing.
3. **Raw Kinetis register names come from the Teensyduino core.** `HAL.cpp` references `RCM_SRS0`, `WDOG_TOVALH`, `WDOG_STCTRLH`, `WDOG_REFRESH`, `ADC0_SC3`, `ADC1_SC3`, `IRQ_FTM1`, `NVIC_ENABLE_IRQ`, and `CORE_PIN…` (`fastio.h`) — all defined by Teensyduino's `cores/teensy3/`, not by Marlin. Do not redefine them; if a build can't find `RCM_SRS0` etc., the wrong core is selected, not a missing Marlin header.
4. **Dual-ADC with a physical-pin→SC1A lookup table.** `adc_start()` indexes a `pin2sc1a[]` array (in `HAL.cpp`) by _physical pin number_; digital-only pins map to `255` and yield `adc_select = -1`. Pin→ADC-channel wiring is fixed by the Teensy 3.5/3.6 silicon — match it against the Teensyduino `pins_teensy.h` numbering if it ever changes.
5. **Watchdog is the Kinetis `WDOG`, refreshed with a two-write sequence.** `watchdog_refresh()` writes `0xA602` then `0xB480` to `WDOG_REFRESH` (hardware-enforced order). The Teensy 3.x has no separate cortex `WDT`; don't port the STM32-style watchdog code here.
6. **Serial objects are native — no custom `Serial` global needed.** Unlike the AT32 HAL, Teensyduino already provides `Serial1`…`Serial3`, `SerialUSB`, and a bare `Serial`. `HAL.h`/`HAL.cpp` only forward-declare `MSerialN` via `ForwardSerial1Class<decltype(SerialN)>` and `USBSerial` (wrapping `SerialUSB`), with `SERIAL_INDEX_MIN 0` / `SERIAL_INDEX_MAX 3`. No `HardwareSerial& Serial = Serial1;` alias hack is required.
7. **SPI wraps the native `SPI` (SPIClass).** `MarlinSPI = SPIClass` (in `MarlinSPI.h`); `HAL_SPI.cpp` drives the Teensyduino `<SPI.h>` `SPI` object via `SPISettings`/`SPI.transfer`. `spiBegin()` configures the SD pins as GPIO. Note `spiSendBlock()` still contains leftover direct `SPDR` writes mixed with `SPI.transfer()` — functional but don't copy the pattern elsewhere.
8. **`reboot()` calls `_reboot_Teensyduino_()`** — a core-provided reset, not a hand-rolled `SCB->AIRCR` jump. Keep using the core helper.
## Conventions
- All HAL source is guarded by `#if defined(__MK64FX512__) || defined(__MK66FX1M0__)` (the chip macro, set by the PlatformIO board JSON — there is no `ARDUINO_ARCH_*` guard for this family).
- Keep HAL changes in `Marlin/src/HAL/TEENSY35_36/` and board pin changes in `Marlin/src/pins/teensy3/pins_TEENSY35_36.h`. Board selection (`BOARD_TEENSY35_36`) lives in `Marlin/src/core/boards.h`.
- The HAL folder has no `README.md` and no vendored framework — framework/platform integration changes are upstream Teensyduino behavior, not something patched in `buildroot/share/PlatformIO/`.
## Related
- Wiki: [[hal-teensy35-36]], [[marlin-src-hal]].
- `Marlin/src/HAL/shared/` — shared HAL APIs (`serial_ports.h`, `HAL_SPI.h`, `eeprom_api.h`) this HAL reuses.
- `Marlin/src/HAL/TEENSY31_32/` and `Marlin/src/HAL/TEENSY40_41/` — sibling Teensy HALs (different silicon, different macros).

View file

@ -0,0 +1,78 @@
# AGENTS.md — TEENSY40_41 HAL
Working notes and conventions for the **TEENSY40_41 HAL** folder (`Marlin/src/HAL/TEENSY40_41/`).
## Build & Test Loop
Always validate with `mftest` (it regenerates `Marlin/Configuration.h` per target, which raw `pio run -e` does not do reliably). The build shortcut for these boards is `teensy41` / `t41` (and `teensy40` / `t40` for the bare 4.0 env). Only the **Teensy 4.1** board has committed test fixtures, so that is the primary green target:
```bash
cd "$(git rev-parse --show-toplevel)"
buildroot/bin/mftest -t teensy41 -n1 -y # config-01 : default BOARD_TEENSY41
buildroot/bin/mftest -t teensy41 -n8 -y # config-08 : dual Z + dual Z endstops
```
The 8 fixtures live in `buildroot/tests/teensy41/config-0[1-8].ini`, all `motherboard = BOARD_TEENSY41`. Run the whole set (or at least config-01 plus a feature-heavy one like config-08) before considering TEENSY40_41 work done.
To compile for the **Teensy 4.0** board specifically (no committed fixtures), build the env directly from a `MOTHERBOARD`:
```bash
buildroot/bin/mftest -t teensy40 -b # -b builds the auto-detected env
# or: pio run -e teensy40
```
Both `teensy40` and `teensy41` envs pull in `src/HAL/TEENSY40_41/` via `ini/teensy.ini`; the only difference is `-DIS_TEENSY40` vs `-DIS_TEENSY41`.
> Do NOT use `rm -rf .pio/build/...` to force a rebuild — the cross-profile write guard blocks it and it is unsafe. Use `pio run -e <env> -t clean` (removes only build artifacts) or just let `mftest` rebuild.
## Framework / Platform Integration (upstream, NOT vendored)
Unlike the AT32 / HC32 HALs, the Teensy Arduino core is **NOT vendored** in the Marlin repo. The build uses the upstream **Teensyduino** core shipped by PlatformIO's `teensy` platform (`platform = teensy@~4.12.0` in `ini/teensy.ini`). The entire HAL source is guarded by `#ifdef __IMXRT1062__` (the chip macro the upstream core defines), not by a Marlin-injected `ARDUINO_ARCH_*` define.
Practical consequences:
- There is **no vendored framework to keep in sync**. Framework/platform fixes are not made in `buildroot/share/PlatformIO/` for this HAL — they belong upstream in Teensyduino. If a Hal-level bug is really a core bug, document it and file it upstream; do not vendor a copy.
- The Teensy core provides `Wire.h`, `SPI.h`, `avr/eeprom.h` (EEPROM emulation), `Serial`, `Serial1`–`Serial8`, and `SerialUSB`. Marlin's `HAL.cpp` wires these into its `MSerialX` / `USBSerial` forwarders (see `HAL.h` serial-port block).
- Build flags come entirely from `ini/teensy.ini` + the HAL's `extra_flags`. There is no Marlin-side `platformio-build-*.py` to patch for size/optimization — the Teensy platform already builds `-O2` correctly.
### Gotchas that are not obvious from the source
1. **`__IMXRT1062__` is the real guard.** `HAL.h`/`HAL.cpp`/`eeprom.cpp` all guard on `__IMXRT1062__`, not `IS_TEENSY40_41`. `IS_TEENSY40_41` / `IS_TEENSY41` / `IS_TEENSY40` are _derived_ macros used for behavior selection inside the HAL (`HAL.h` sets `IS_TEENSY41` unless `IS_TEENSY40` is defined). Don't add `ARDUINO_ARCH_TEENSY` guards — they don't exist here.
2. **TFT displays are unsupported.** `inc/SanityCheck.h` hard-errors on `HAS_SPI_TFT || HAS_FSMC_TFT` ("TFT displays are not available for Teensy 4.0/4.1"). Don't try to enable an SPI/FSMC TFT on this HAL.
3. **`EMERGENCY_PARSER` is not implemented.** SanityCheck errors out if `EMERGENCY_PARSER` is enabled. Hosts must rely on the normal command queue, not the emergency-parser fast path.
4. **TMC220x software serial is unsupported.** `HAS_TMC_SW_SERIAL` errors out. TMC drivers must use hardware UART or SPI (the `MarlinSPI.h` / `HAL_SPI.cpp` path).
5. **`POSTMORTEM_DEBUGGING` and `SERIAL_STATS_*` are unsupported.** Both error out in SanityCheck. Don't enable them for Teensy 4.x boards.
6. **EEPROM uses the Teensyduino emulated EEPROM, not SD-card emulation.** `eeprom.cpp` is guarded by `USE_WIRED_EEPROM` and includes the upstream `<avr/eeprom.h>` (Teensyduino's flash-backed emulation). It does **not** use `SDCARD_EEPROM_EMULATION`; per-board `pins_teensy*` files do not need to define an SD-backed store. `MARLIN_EEPROM_SIZE` defaults to `E2END + 1` from the core.
7. **`PSTR` is redefined to defeat PROGMEM.** `HAL.h` does `#undef PSTR` / `#define PSTR(str) ({static const char *data = (str); &data[0];})` because the IMXRT1062 has linear address space and the AVR `PSTR`/progmem model does not apply. String literals in this HAL behave like normal RAM pointers — do not assume `__flash`/`PROGMEM` semantics.
8. **`sq()` is redefined.** `HAL.h` `#undef sq` / `#define sq(x) ((x)*(x))` to match the Teensy core's math macros and avoid collisions with the Arduino `sq`.
9. **ADC pins map to a different index range.** `analogInputToDigitalPin(p)` returns `p + 54` for `p < 12` (Teensy's analog pins are numbered 54+), else `-1`. Pin numbers here are the Teensy digital pin numbers, not the AVR-style `A0`→`0` scheme.
10. **FastIO goes through `digitalRead`/`digitalWrite`, not direct-port manipulation.** `fastio.h` implements `READ`/`WRITE`/`SET_*` as calls to the Teensy GPIO functions (no AVR-style port registers). `is_output(pin)` is a real helper in `HAL.cpp` used by `_GET_MODE`/`IS_INPUT`/`IS_OUTPUT`. PWM capability is `digitalPinHasPWM(P)`.
11. **PWM frequency is set per-pin via the Teensy pulse API.** `set_pwm_frequency()` wraps `analogWriteFrequency()`; `set_pwm_duty()` wraps `analogWrite()`. The SanityCheck emits a `#warning` if `FAST_PWM_FAN` is left at the 1000 Hz default (suggesting a higher, quieter frequency) and another `#warning` that `SPINDLE_LASER_USE_PWM` is untested. See https://www.pjrc.com/teensy/td_pulse.html.
12. **Serial port indices are 0–8, with USB and Ethernet aliases.** `HAL.h` defines `SERIAL_INDEX_MIN 0` / `SERIAL_INDEX_MAX 8`, `Serial0` = `Serial`, `USBSerial` (forwarding `SerialUSB`), and `ETH_SERIAL_PORT` = `ethernet.telnetClient`. `BAUD_RATE_GCODE` is rejected when `SERIAL_PORT_2 == -2` (the Ethernet serial port).
13. **No `FRAME` / variant linker script surgery needed.** The Teensy platform supplies the correct flash/RAM linker script for both 4.0 (1 MB flash / 512 KB RAM) and 4.1 (1 MB / 8 MB PSRAM variants). There is no per-board linker-script assignment to maintain in the Marlin repo.
## Conventions
- All HAL source is guarded by `#ifdef __IMXRT1062__`. Select 4.0-vs-4.1 behavior with `IS_TEENSY40` / `IS_TEENSY41` (set from `extra_flags` in `ini/teensy.ini`).
- Keep HAL implementation in `Marlin/src/HAL/TEENSY40_41/` and board pin files in `Marlin/src/pins/teensy40_41/` (and any shared `pins_teensy*` helpers).
- Because the Arduino core is upstream (not vendored), do NOT mirror framework changes into `buildroot/share/PlatformIO/` for this HAL — there is nothing to mirror.
- Don't paper over SanityCheck errors with config edits; the errors document real unsupported features (TFT, emergency parser, TMC SW serial, postmortem, serial stats).
## Related
- `ini/teensy.ini` — env definitions for `teensy31` / `teensy35` / `teensy36` / `teensy40` / `teensy41`.
- `buildroot/tests/teensy41/*.ini` — the committed test fixtures for this HAL.
- Wiki: [[hal-teensy40-41]], [[marlin-src-hal]].
- `Marlin/src/HAL/shared/` — shared HAL APIs (`eeprom_api`, SPI helpers, serial ports) the TEENSY40_41 HAL reuses.

View file

@ -249,7 +249,7 @@ This can be implemented in C++ as:
public:
unsigned int ticker;
OversampledBresenhan(const long& inDividend, const long& inDivisor, int rate) {
OversampledBresenham(const long& inDividend, const long& inDivisor, int rate) {
ticker = 0;
divisor = inDivisor;
dividend = inDividend;