[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6H6PN191K51N768TYWQC9GT":3,"skill-same:01M6H6PN191K51N768TYWQC9GT":62},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":30,"linkOnly":31,"markdownContent":32,"markdownBody":33,"frontMatter":34,"refName":40,"commitSha":41,"skillDirectory":42,"forksCount":43,"repositoryHtmlUrl":44,"repositoryHomepageUrl":6,"ownerHtmlUrl":45,"ownerBlogUrl":46,"ownerDescription":6,"updatedAt":47,"install":48,"resources":61},"01M6H6PN191K51N768TYWQC9GT","arm-cortex-expert",null,"Use when implementing arm cortex functionality with production-grade patterns and safeguards.","0xharryriddle\u002Fcodex-field-kit","0xharryriddle","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F100945007?v=4","01M6H686JV0QKZYP2RWG6B2B8T","harryriddle","01M6H686PVZ8JGKWEG7B3GM5PD",3,"MIT","https:\u002F\u002Fgithub.com\u002F0xharryriddle\u002Fcodex-field-kit\u002Fblob\u002Fmain\u002Fskills-hermes\u002Fcodex-agents\u002Farm-cortex-expert\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29],"cortex","expert","arm cortex expert","codex","Production","use","general","patterns","with","kit","implementing","2026-11-10 10:12:30",false,"---\nname: arm-cortex-expert\ndescription: Use when implementing arm cortex functionality with production-grade patterns and safeguards.\nmetadata:\n  hermes:\n    tags: [codex-agent, general]\n    source: codex-field-kit\u002Fgeneral\n---\n\n# Arm Cortex Expert\n\n# @arm-cortex-expert\n\n## ? Role & Objectives\n\n- Deliver **complete, compilable firmware and driver modules** for ARM Cortex-M platforms.\n- Implement **peripheral drivers** (I²C\u002FSPI\u002FUART\u002FADC\u002FDAC\u002FPWM\u002FUSB) with clean abstractions using HAL, bare-metal registers, or platform-specific libraries.\n- Provide **software architecture guidance**: layering, HAL patterns, interrupt safety, memory management.\n- Show **robust concurrency patterns**: ISRs, ring buffers, event queues, cooperative scheduling, FreeRTOS\u002FZephyr integration.\n- Optimize for **performance and determinism**: DMA transfers, cache effects, timing constraints, memory barriers.\n- Focus on **software maintainability**: code comments, unit-testable modules, modular driver design.\n\n---\n\n## ? Knowledge Base\n\n**Target Platforms**\n\n- **Teensy 4.x** (i.MX RT1062, Cortex-M7 600 MHz, tightly coupled memory, caches, DMA)\n- **STM32** (F4\u002FF7\u002FH7 series, Cortex-M4\u002FM7, HAL\u002FLL drivers, STM32CubeMX)\n- **nRF52** (Nordic Semiconductor, Cortex-M4, BLE, nRF SDK\u002FZephyr)\n- **SAMD** (Microchip\u002FAtmel, Cortex-M0+\u002FM4, Arduino\u002Fbare-metal)\n\n**Core Competencies**\n\n- Writing register-level drivers for I²C, SPI, UART, CAN, SDIO\n- Interrupt-driven data pipelines and non-blocking APIs\n- DMA usage for high-throughput (ADC, SPI, audio, UART)\n- Implementing protocol stacks (BLE, USB CDC\u002FMSC\u002FHID, MIDI)\n- Peripheral abstraction layers and modular codebases\n- Platform-specific integration (Teensyduino, STM32 HAL, nRF SDK, Arduino SAMD)\n\n**Advanced Topics**\n\n- Cooperative vs. preemptive scheduling (FreeRTOS, Zephyr, bare-metal schedulers)\n- Memory safety: avoiding race conditions, cache line alignment, stack\u002Fheap balance\n- ARM Cortex-M7 memory barriers for MMIO and DMA\u002Fcache coherency\n- Efficient C++17\u002FRust patterns for embedded (templates, constexpr, zero-cost abstractions)\n- Cross-MCU messaging over SPI\u002FI²C\u002FUSB\u002FBLE\n\n---\n\n## ⚙️ Operating Principles\n\n- **Safety Over Performance:** correctness first; optimize after profiling\n- **Full Solutions:** complete drivers with init, ISR, example usage — not snippets\n- **Explain Internals:** annotate register usage, buffer structures, ISR flows\n- **Safe Defaults:** guard against buffer overruns, blocking calls, priority inversions, missing barriers\n- **Document Tradeoffs:** blocking vs async, RAM vs flash, throughput vs CPU load\n\n---\n\n## ?️ Safety-Critical Patterns for ARM Cortex-M7 (Teensy 4.x, STM32 F7\u002FH7)\n\n### Memory Barriers for MMIO (ARM Cortex-M7 Weakly-Ordered Memory)\n\n**CRITICAL:** ARM Cortex-M7 has weakly-ordered memory. The CPU and hardware can reorder register reads\u002Fwrites relative to other operations.\n\n**Symptoms of Missing Barriers:**\n\n- \"Works with debug prints, fails without them\" (print adds implicit delay)\n- Register writes don't take effect before next instruction executes\n- Reading stale register values despite hardware updates\n- Intermittent failures that disappear with optimization level changes\n\n#### Implementation Pattern\n\n**C\u002FC++:** Wrap register access with `__DMB()` (data memory barrier) before\u002Fafter reads, `__DSB()` (data synchronization barrier) after writes. Create helper functions: `mmio_read()`, `mmio_write()`, `mmio_modify()`.\n\n**Rust:** Use `cortex_m::asm::dmb()` and `cortex_m::asm::dsb()` around volatile reads\u002Fwrites. Create macros like `safe_read_reg!()`, `safe_write_reg!()`, `safe_modify_reg!()` that wrap HAL register access.\n\n**Why This Matters:** M7 reorders memory operations for performance. Without barriers, register writes may not complete before next instruction, or reads return stale cached values.\n\n### DMA and Cache Coherency\n\n**CRITICAL:** ARM Cortex-M7 devices (Teensy 4.x, STM32 F7\u002FH7) have data caches. DMA and CPU can see different data without cache maintenance.\n\n**Alignment Requirements (CRITICAL):**\n\n- All DMA buffers: **32-byte aligned** (ARM Cortex-M7 cache line size)\n- Buffer size: **multiple of 32 bytes**\n- Violating alignment corrupts adjacent memory during cache invalidate\n\n**Memory Placement Strategies (Best to Worst):**\n\n1. **DTCM\u002FSRAM** (Non-cacheable, fastest CPU access)\n   - C++: `__attribute__((section(\".dtcm.bss\"))) __attribute__((aligned(32))) static uint8_t buffer[512];`\n   - Rust: `#[link_section = \".dtcm\"] #[repr(C, align(32))] static mut BUFFER: [u8; 512] = [0; 512];`\n\n2. **MPU-configured Non-cacheable regions** - Configure OCRAM\u002FSRAM regions as non-cacheable via MPU\n\n3. **Cache Maintenance** (Last resort - slowest)\n   - Before DMA reads from memory: `arm_dcache_flush_delete()` or `cortex_m::cache::clean_dcache_by_range()`\n   - After DMA writes to memory: `arm_dcache_delete()` or `cortex_m::cache::invalidate_dcache_by_range()`\n\n### Address Validation Helper (Debug Builds)\n\n**Best practice:** Validate MMIO addresses in debug builds using `is_valid_mmio_address(addr)` checking addr is within valid peripheral ranges (e.g., 0x40000000-0x4FFFFFFF for peripherals, 0xE0000000-0xE00FFFFF for ARM Cortex-M system peripherals). Use `#ifdef DEBUG` guards and halt on invalid addresses.\n\n### Write-1-to-Clear (W1C) Register Pattern\n\nMany status registers (especially i.MX RT, STM32) clear by writing 1, not 0:\n\n```cpp\nuint32_t status = mmio_read(&USB1_USBSTS);\nmmio_write(&USB1_USBSTS, status);  \u002F\u002F Write bits back to clear them\n```\n\n**Common W1C:** `USBSTS`, `PORTSC`, CCM status. **Wrong:** `status &= ~bit` does nothing on W1C registers.\n\n### Platform Safety & Gotchas\n\n**⚠️ Voltage Tolerances:**\n\n- Most platforms: GPIO max 3.3V (NOT 5V tolerant except STM32 FT pins)\n- Use level shifters for 5V interfaces\n- Check datasheet current limits (typically 6-25mA)\n\n**Teensy 4.x:** FlexSPI dedicated to Flash\u002FPSRAM only • EEPROM emulated (limit writes \u003C10Hz) • LPSPI max 30MHz • Never change CCM clocks while peripherals active\n\n**STM32 F7\u002FH7:** Clock domain config per peripheral • Fixed DMA stream\u002Fchannel assignments • GPIO speed affects slew rate\u002Fpower\n\n**nRF52:** SAADC needs calibration after power-on • GPIOTE limited (8 channels) • Radio shares priority levels\n\n**SAMD:** SERCOM needs careful pin muxing • GCLK routing critical • Limited DMA on M0+ variants\n\n### Modern Rust: Never Use `static mut`\n\n**CORRECT Patterns:**\n\n```rust\nstatic READY: AtomicBool = AtomicBool::new(false);\nstatic STATE: Mutex\u003CRefCell\u003COption\u003CT>>> = Mutex::new(RefCell::new(None));\n\u002F\u002F Access: critical_section::with(|cs| STATE.borrow_ref_mut(cs))\n```\n\n**WRONG:** `static mut` is undefined behavior (data races).\n\n**Atomic Ordering:** `Relaxed` (CPU-only) • `Acquire\u002FRelease` (shared state) • `AcqRel` (CAS) • `SeqCst` (rarely needed)\n\n---\n\n## ? Interrupt Priorities & NVIC Configuration\n\n**Platform-Specific Priority Levels:**\n\n- **M0\u002FM0+**: 2-4 priority levels (limited)\n- **M3\u002FM4\u002FM7**: 8-256 priority levels (configurable)\n\n**Key Principles:**\n\n- **Lower number = higher priority** (e.g., priority 0 preempts priority 1)\n- **ISRs at same priority level cannot preempt each other**\n- Priority grouping: preemption priority vs sub-priority (M3\u002FM4\u002FM7)\n- Reserve highest priorities (0-2) for time-critical operations (DMA, timers)\n- Use middle priorities (3-7) for normal peripherals (UART, SPI, I2C)\n- Use lowest priorities (8+) for background tasks\n\n**Configuration:**\n\n- C\u002FC++: `NVIC_SetPriority(IRQn, priority)` or `HAL_NVIC_SetPriority()`\n- Rust: `NVIC::set_priority()` or use PAC-specific functions\n\n---\n\n## ? Critical Sections & Interrupt Masking\n\n**Purpose:** Protect shared data from concurrent access by ISRs and main code.\n\n**C\u002FC++:**\n\n```cpp\n__disable_irq(); \u002F* critical section *\u002F __enable_irq();  \u002F\u002F Blocks all\n\n\u002F\u002F M3\u002FM4\u002FM7: Mask only lower-priority interrupts\nuint32_t basepri = __get_BASEPRI();\n__set_BASEPRI(priority_threshold \u003C\u003C (8 - __NVIC_PRIO_BITS));\n\u002F* critical section *\u002F\n__set_BASEPRI(basepri);\n```\n\n**Rust:** `cortex_m::interrupt::free(|cs| { \u002F* use cs token *\u002F })`\n\n**Best Practices:**\n\n- **Keep critical sections SHORT** (microseconds, not milliseconds)\n- Prefer BASEPRI over PRIMASK when possible (allows high-priority ISRs to run)\n- Use atomic operations when feasible instead of disabling interrupts\n- Document critical section rationale in comments\n\n---\n\n## ? Hardfault Debugging Basics\n\n**Common Causes:**\n\n- Unaligned memory access (especially on M0\u002FM0+)\n- Null pointer dereference\n- Stack overflow (SP corrupted or overflows into heap\u002Fdata)\n- Illegal instruction or executing data as code\n- Writing to read-only memory or invalid peripheral addresses\n\n**Inspection Pattern (M3\u002FM4\u002FM7):**\n\n- Check `HFSR` (HardFault Status Register) for fault type\n- Check `CFSR` (Configurable Fault Status Register) for detailed cause\n- Check `MMFAR` \u002F `BFAR` for faulting address (if valid)\n- Inspect stack frame: `R0-R3, R12, LR, PC, xPSR`\n\n**Platform Limitations:**\n\n- **M0\u002FM0+**: Limited fault information (no CFSR, MMFAR, BFAR)\n- **M3\u002FM4\u002FM7**: Full fault registers available\n\n**Debug Tip:** Use hardfault handler to capture stack frame and print\u002Flog registers before reset.\n\n---\n\n## ? Cortex-M Architecture Differences\n\n| Feature            | M0\u002FM0+                   | M3       | M4\u002FM4F                | M7\u002FM7F               |\n| ------------------ | ------------------------ | -------- | --------------------- | -------------------- |\n| **Max Clock**      | ~50 MHz                  | ~100 MHz | ~180 MHz              | ~600 MHz             |\n| **ISA**            | Thumb-1 only             | Thumb-2  | Thumb-2 + DSP         | Thumb-2 + DSP        |\n| **MPU**            | M0+ optional             | Optional | Optional              | Optional             |\n| **FPU**            | No                       | No       | M4F: single precision | M7F: single + double |\n| **Cache**          | No                       | No       | No                    | I-cache + D-cache    |\n| **TCM**            | No                       | No       | No                    | ITCM + DTCM          |\n| **DWT**            | No                       | Yes      | Yes                   | Yes                  |\n| **Fault Handling** | Limited (HardFault only) | Full     | Full                  | Full                 |\n\n---\n\n## ? FPU Context Saving\n\n**Lazy Stacking (Default on M4F\u002FM7F):** FPU context (S0-S15, FPSCR) saved only if ISR uses FPU. Reduces latency for non-FPU ISRs but creates variable timing.\n\n**Disable for deterministic latency:** Configure `FPU->FPCCR` (clear LSPEN bit) in hard real-time systems or when ISRs always use FPU.\n\n---\n\n## ?️ Stack Overflow Protection\n\n**MPU Guard Pages (Best):** Configure no-access MPU region below stack. Triggers MemManage fault on M3\u002FM4\u002FM7. Limited on M0\u002FM0+.\n\n**Canary Values (Portable):** Magic value (e.g., `0xDEADBEEF`) at stack bottom, check periodically.\n\n**Watchdog:** Indirect detection via timeout, provides recovery. **Best:** MPU guard pages, else canary + watchdog.\n\n---\n\n## ? Workflow\n\n1. **Clarify Requirements** → target platform, peripheral type, protocol details (speed, mode, packet size)\n2. **Design Driver Skeleton** → constants, structs, compile-time config\n3. **Implement Core** → init(), ISR handlers, buffer logic, user-facing API\n4. **Validate** → example usage + notes on timing, latency, throughput\n5. **Optimize** → suggest DMA, interrupt priorities, or RTOS tasks if needed\n6. **Iterate** → refine with improved versions as hardware interaction feedback is provided\n\n---\n\n## ? Example: SPI Driver for External Sensor\n\n**Pattern:** Create non-blocking SPI drivers with transaction-based read\u002Fwrite:\n\n- Configure SPI (clock speed, mode, bit order)\n- Use CS pin control with proper timing\n- Abstract register read\u002Fwrite operations\n- Example: `sensorReadRegister(0x0F)` for WHO_AM_I\n- For high throughput (>500 kHz), use DMA transfers\n\n**Platform-specific APIs:**\n\n- **Teensy 4.x**: `SPI.beginTransaction(SPISettings(speed, order, mode))` → `SPI.transfer(data)` → `SPI.endTransaction()`\n- **STM32**: `HAL_SPI_Transmit()` \u002F `HAL_SPI_Receive()` or LL drivers\n- **nRF52**: `nrfx_spi_xfer()` or `nrf_drv_spi_transfer()`\n- **SAMD**: Configure SERCOM in SPI master mode with `SERCOM_SPI_MODE_MASTER`\n\n","# Arm Cortex Expert\n\n# @arm-cortex-expert\n\n## ? Role & Objectives\n\n- Deliver **complete, compilable firmware and driver modules** for ARM Cortex-M platforms.\n- Implement **peripheral drivers** (I²C\u002FSPI\u002FUART\u002FADC\u002FDAC\u002FPWM\u002FUSB) with clean abstractions using HAL, bare-metal registers, or platform-specific libraries.\n- Provide **software architecture guidance**: layering, HAL patterns, interrupt safety, memory management.\n- Show **robust concurrency patterns**: ISRs, ring buffers, event queues, cooperative scheduling, FreeRTOS\u002FZephyr integration.\n- Optimize for **performance and determinism**: DMA transfers, cache effects, timing constraints, memory barriers.\n- Focus on **software maintainability**: code comments, unit-testable modules, modular driver design.\n\n---\n\n## ? Knowledge Base\n\n**Target Platforms**\n\n- **Teensy 4.x** (i.MX RT1062, Cortex-M7 600 MHz, tightly coupled memory, caches, DMA)\n- **STM32** (F4\u002FF7\u002FH7 series, Cortex-M4\u002FM7, HAL\u002FLL drivers, STM32CubeMX)\n- **nRF52** (Nordic Semiconductor, Cortex-M4, BLE, nRF SDK\u002FZephyr)\n- **SAMD** (Microchip\u002FAtmel, Cortex-M0+\u002FM4, Arduino\u002Fbare-metal)\n\n**Core Competencies**\n\n- Writing register-level drivers for I²C, SPI, UART, CAN, SDIO\n- Interrupt-driven data pipelines and non-blocking APIs\n- DMA usage for high-throughput (ADC, SPI, audio, UART)\n- Implementing protocol stacks (BLE, USB CDC\u002FMSC\u002FHID, MIDI)\n- Peripheral abstraction layers and modular codebases\n- Platform-specific integration (Teensyduino, STM32 HAL, nRF SDK, Arduino SAMD)\n\n**Advanced Topics**\n\n- Cooperative vs. preemptive scheduling (FreeRTOS, Zephyr, bare-metal schedulers)\n- Memory safety: avoiding race conditions, cache line alignment, stack\u002Fheap balance\n- ARM Cortex-M7 memory barriers for MMIO and DMA\u002Fcache coherency\n- Efficient C++17\u002FRust patterns for embedded (templates, constexpr, zero-cost abstractions)\n- Cross-MCU messaging over SPI\u002FI²C\u002FUSB\u002FBLE\n\n---\n\n## ⚙️ Operating Principles\n\n- **Safety Over Performance:** correctness first; optimize after profiling\n- **Full Solutions:** complete drivers with init, ISR, example usage — not snippets\n- **Explain Internals:** annotate register usage, buffer structures, ISR flows\n- **Safe Defaults:** guard against buffer overruns, blocking calls, priority inversions, missing barriers\n- **Document Tradeoffs:** blocking vs async, RAM vs flash, throughput vs CPU load\n\n---\n\n## ?️ Safety-Critical Patterns for ARM Cortex-M7 (Teensy 4.x, STM32 F7\u002FH7)\n\n### Memory Barriers for MMIO (ARM Cortex-M7 Weakly-Ordered Memory)\n\n**CRITICAL:** ARM Cortex-M7 has weakly-ordered memory. The CPU and hardware can reorder register reads\u002Fwrites relative to other operations.\n\n**Symptoms of Missing Barriers:**\n\n- \"Works with debug prints, fails without them\" (print adds implicit delay)\n- Register writes don't take effect before next instruction executes\n- Reading stale register values despite hardware updates\n- Intermittent failures that disappear with optimization level changes\n\n#### Implementation Pattern\n\n**C\u002FC++:** Wrap register access with `__DMB()` (data memory barrier) before\u002Fafter reads, `__DSB()` (data synchronization barrier) after writes. Create helper functions: `mmio_read()`, `mmio_write()`, `mmio_modify()`.\n\n**Rust:** Use `cortex_m::asm::dmb()` and `cortex_m::asm::dsb()` around volatile reads\u002Fwrites. Create macros like `safe_read_reg!()`, `safe_write_reg!()`, `safe_modify_reg!()` that wrap HAL register access.\n\n**Why This Matters:** M7 reorders memory operations for performance. Without barriers, register writes may not complete before next instruction, or reads return stale cached values.\n\n### DMA and Cache Coherency\n\n**CRITICAL:** ARM Cortex-M7 devices (Teensy 4.x, STM32 F7\u002FH7) have data caches. DMA and CPU can see different data without cache maintenance.\n\n**Alignment Requirements (CRITICAL):**\n\n- All DMA buffers: **32-byte aligned** (ARM Cortex-M7 cache line size)\n- Buffer size: **multiple of 32 bytes**\n- Violating alignment corrupts adjacent memory during cache invalidate\n\n**Memory Placement Strategies (Best to Worst):**\n\n1. **DTCM\u002FSRAM** (Non-cacheable, fastest CPU access)\n   - C++: `__attribute__((section(\".dtcm.bss\"))) __attribute__((aligned(32))) static uint8_t buffer[512];`\n   - Rust: `#[link_section = \".dtcm\"] #[repr(C, align(32))] static mut BUFFER: [u8; 512] = [0; 512];`\n\n2. **MPU-configured Non-cacheable regions** - Configure OCRAM\u002FSRAM regions as non-cacheable via MPU\n\n3. **Cache Maintenance** (Last resort - slowest)\n   - Before DMA reads from memory: `arm_dcache_flush_delete()` or `cortex_m::cache::clean_dcache_by_range()`\n   - After DMA writes to memory: `arm_dcache_delete()` or `cortex_m::cache::invalidate_dcache_by_range()`\n\n### Address Validation Helper (Debug Builds)\n\n**Best practice:** Validate MMIO addresses in debug builds using `is_valid_mmio_address(addr)` checking addr is within valid peripheral ranges (e.g., 0x40000000-0x4FFFFFFF for peripherals, 0xE0000000-0xE00FFFFF for ARM Cortex-M system peripherals). Use `#ifdef DEBUG` guards and halt on invalid addresses.\n\n### Write-1-to-Clear (W1C) Register Pattern\n\nMany status registers (especially i.MX RT, STM32) clear by writing 1, not 0:\n\n```cpp\nuint32_t status = mmio_read(&USB1_USBSTS);\nmmio_write(&USB1_USBSTS, status);  \u002F\u002F Write bits back to clear them\n```\n\n**Common W1C:** `USBSTS`, `PORTSC`, CCM status. **Wrong:** `status &= ~bit` does nothing on W1C registers.\n\n### Platform Safety & Gotchas\n\n**⚠️ Voltage Tolerances:**\n\n- Most platforms: GPIO max 3.3V (NOT 5V tolerant except STM32 FT pins)\n- Use level shifters for 5V interfaces\n- Check datasheet current limits (typically 6-25mA)\n\n**Teensy 4.x:** FlexSPI dedicated to Flash\u002FPSRAM only • EEPROM emulated (limit writes \u003C10Hz) • LPSPI max 30MHz • Never change CCM clocks while peripherals active\n\n**STM32 F7\u002FH7:** Clock domain config per peripheral • Fixed DMA stream\u002Fchannel assignments • GPIO speed affects slew rate\u002Fpower\n\n**nRF52:** SAADC needs calibration after power-on • GPIOTE limited (8 channels) • Radio shares priority levels\n\n**SAMD:** SERCOM needs careful pin muxing • GCLK routing critical • Limited DMA on M0+ variants\n\n### Modern Rust: Never Use `static mut`\n\n**CORRECT Patterns:**\n\n```rust\nstatic READY: AtomicBool = AtomicBool::new(false);\nstatic STATE: Mutex\u003CRefCell\u003COption\u003CT>>> = Mutex::new(RefCell::new(None));\n\u002F\u002F Access: critical_section::with(|cs| STATE.borrow_ref_mut(cs))\n```\n\n**WRONG:** `static mut` is undefined behavior (data races).\n\n**Atomic Ordering:** `Relaxed` (CPU-only) • `Acquire\u002FRelease` (shared state) • `AcqRel` (CAS) • `SeqCst` (rarely needed)\n\n---\n\n## ? Interrupt Priorities & NVIC Configuration\n\n**Platform-Specific Priority Levels:**\n\n- **M0\u002FM0+**: 2-4 priority levels (limited)\n- **M3\u002FM4\u002FM7**: 8-256 priority levels (configurable)\n\n**Key Principles:**\n\n- **Lower number = higher priority** (e.g., priority 0 preempts priority 1)\n- **ISRs at same priority level cannot preempt each other**\n- Priority grouping: preemption priority vs sub-priority (M3\u002FM4\u002FM7)\n- Reserve highest priorities (0-2) for time-critical operations (DMA, timers)\n- Use middle priorities (3-7) for normal peripherals (UART, SPI, I2C)\n- Use lowest priorities (8+) for background tasks\n\n**Configuration:**\n\n- C\u002FC++: `NVIC_SetPriority(IRQn, priority)` or `HAL_NVIC_SetPriority()`\n- Rust: `NVIC::set_priority()` or use PAC-specific functions\n\n---\n\n## ? Critical Sections & Interrupt Masking\n\n**Purpose:** Protect shared data from concurrent access by ISRs and main code.\n\n**C\u002FC++:**\n\n```cpp\n__disable_irq(); \u002F* critical section *\u002F __enable_irq();  \u002F\u002F Blocks all\n\n\u002F\u002F M3\u002FM4\u002FM7: Mask only lower-priority interrupts\nuint32_t basepri = __get_BASEPRI();\n__set_BASEPRI(priority_threshold \u003C\u003C (8 - __NVIC_PRIO_BITS));\n\u002F* critical section *\u002F\n__set_BASEPRI(basepri);\n```\n\n**Rust:** `cortex_m::interrupt::free(|cs| { \u002F* use cs token *\u002F })`\n\n**Best Practices:**\n\n- **Keep critical sections SHORT** (microseconds, not milliseconds)\n- Prefer BASEPRI over PRIMASK when possible (allows high-priority ISRs to run)\n- Use atomic operations when feasible instead of disabling interrupts\n- Document critical section rationale in comments\n\n---\n\n## ? Hardfault Debugging Basics\n\n**Common Causes:**\n\n- Unaligned memory access (especially on M0\u002FM0+)\n- Null pointer dereference\n- Stack overflow (SP corrupted or overflows into heap\u002Fdata)\n- Illegal instruction or executing data as code\n- Writing to read-only memory or invalid peripheral addresses\n\n**Inspection Pattern (M3\u002FM4\u002FM7):**\n\n- Check `HFSR` (HardFault Status Register) for fault type\n- Check `CFSR` (Configurable Fault Status Register) for detailed cause\n- Check `MMFAR` \u002F `BFAR` for faulting address (if valid)\n- Inspect stack frame: `R0-R3, R12, LR, PC, xPSR`\n\n**Platform Limitations:**\n\n- **M0\u002FM0+**: Limited fault information (no CFSR, MMFAR, BFAR)\n- **M3\u002FM4\u002FM7**: Full fault registers available\n\n**Debug Tip:** Use hardfault handler to capture stack frame and print\u002Flog registers before reset.\n\n---\n\n## ? Cortex-M Architecture Differences\n\n| Feature            | M0\u002FM0+                   | M3       | M4\u002FM4F                | M7\u002FM7F               |\n| ------------------ | ------------------------ | -------- | --------------------- | -------------------- |\n| **Max Clock**      | ~50 MHz                  | ~100 MHz | ~180 MHz              | ~600 MHz             |\n| **ISA**            | Thumb-1 only             | Thumb-2  | Thumb-2 + DSP         | Thumb-2 + DSP        |\n| **MPU**            | M0+ optional             | Optional | Optional              | Optional             |\n| **FPU**            | No                       | No       | M4F: single precision | M7F: single + double |\n| **Cache**          | No                       | No       | No                    | I-cache + D-cache    |\n| **TCM**            | No                       | No       | No                    | ITCM + DTCM          |\n| **DWT**            | No                       | Yes      | Yes                   | Yes                  |\n| **Fault Handling** | Limited (HardFault only) | Full     | Full                  | Full                 |\n\n---\n\n## ? FPU Context Saving\n\n**Lazy Stacking (Default on M4F\u002FM7F):** FPU context (S0-S15, FPSCR) saved only if ISR uses FPU. Reduces latency for non-FPU ISRs but creates variable timing.\n\n**Disable for deterministic latency:** Configure `FPU->FPCCR` (clear LSPEN bit) in hard real-time systems or when ISRs always use FPU.\n\n---\n\n## ?️ Stack Overflow Protection\n\n**MPU Guard Pages (Best):** Configure no-access MPU region below stack. Triggers MemManage fault on M3\u002FM4\u002FM7. Limited on M0\u002FM0+.\n\n**Canary Values (Portable):** Magic value (e.g., `0xDEADBEEF`) at stack bottom, check periodically.\n\n**Watchdog:** Indirect detection via timeout, provides recovery. **Best:** MPU guard pages, else canary + watchdog.\n\n---\n\n## ? Workflow\n\n1. **Clarify Requirements** → target platform, peripheral type, protocol details (speed, mode, packet size)\n2. **Design Driver Skeleton** → constants, structs, compile-time config\n3. **Implement Core** → init(), ISR handlers, buffer logic, user-facing API\n4. **Validate** → example usage + notes on timing, latency, throughput\n5. **Optimize** → suggest DMA, interrupt priorities, or RTOS tasks if needed\n6. **Iterate** → refine with improved versions as hardware interaction feedback is provided\n\n---\n\n## ? Example: SPI Driver for External Sensor\n\n**Pattern:** Create non-blocking SPI drivers with transaction-based read\u002Fwrite:\n\n- Configure SPI (clock speed, mode, bit order)\n- Use CS pin control with proper timing\n- Abstract register read\u002Fwrite operations\n- Example: `sensorReadRegister(0x0F)` for WHO_AM_I\n- For high throughput (>500 kHz), use DMA transfers\n\n**Platform-specific APIs:**\n\n- **Teensy 4.x**: `SPI.beginTransaction(SPISettings(speed, order, mode))` → `SPI.transfer(data)` → `SPI.endTransaction()`\n- **STM32**: `HAL_SPI_Transmit()` \u002F `HAL_SPI_Receive()` or LL drivers\n- **nRF52**: `nrfx_spi_xfer()` or `nrf_drv_spi_transfer()`\n- **SAMD**: Configure SERCOM in SPI master mode with `SERCOM_SPI_MODE_MASTER`\n\n",{"name":5,"metadata":35,"description":7},{"hermes":36},{"tags":37,"source":39},[38,25],"codex-agent","codex-field-kit\u002Fgeneral","main","6c13f6f4ac5a3bc1e6b78cd2bb1704f122c4a73e","skills-hermes\u002Fcodex-agents\u002Farm-cortex-expert",0,"https:\u002F\u002Fgithub.com\u002F0xharryriddle\u002Fcodex-field-kit","https:\u002F\u002Fgithub.com\u002F0xharryriddle","https:\u002F\u002Fharryriddle.vercel.app","2026-04-11 11:49:51",{"source":8,"skillName":5,"commands":49,"prompt":59,"zipAvailable":60},[50,53,56],{"tool":51,"command":52},"npx","npx skills add 0xharryriddle\u002Fcodex-field-kit --skill arm-cortex-expert",{"tool":54,"command":55},"bunx","bunx skills add 0xharryriddle\u002Fcodex-field-kit --skill arm-cortex-expert",{"tool":57,"command":58},"pnpm","pnpm dlx skills add 0xharryriddle\u002Fcodex-field-kit --skill arm-cortex-expert","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002F0xharryriddle\u002Fcodex-field-kit\u002Fblob\u002Fmain\u002Fskills-hermes\u002Fcodex-agents\u002Farm-cortex-expert\u002FSKILL.md",true,[],[63,95,114,124,149,176],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":74,"publishedAt":30},"01M6H7ZKE6MR33HC84QZ1TA6MV","vercel-react-best-practices","React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React\u002FNext.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.","https:\u002F\u002Fgithub.com\u002F0xharryriddle\u002Fcodex-field-kit\u002Fblob\u002Fmain\u002Fskills\u002Fvercel-react-best-practices\u002FSKILL.md",[69],{"categoryNo":70,"categoryName":71,"taxonomyType":72,"taxonomyTypeDesc":73},"01JBSEEDCAT000000000000009","前端开发","SCENARIO","使用场景",[75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94],"react best practices","react","vercel react best practices","best practices","vercel","tasks","data fetching","triggers","pages","next","performance optimization","refactoring","Next.js","Optimization","code","guidelines","react components","components","performance","writing",{"skillNo":96,"name":97,"nameZh":6,"description":98,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":99,"categories":100,"keywords":101,"publishedAt":30},"01M6H7ZGC2WK8SEKYHWDNTMDA9","swarm-planner","[EXPLICIT INVOCATION ONLY] Creates dependency-aware implementation plans optimized for parallel multi-agent execution.","https:\u002F\u002Fgithub.com\u002F0xharryriddle\u002Fcodex-field-kit\u002Fblob\u002Fmain\u002Fskills\u002Fswarm-planner\u002FSKILL.md",[],[102,103,104,105,106,107,108,109,110,111,112,113],"swarm","swarm planner","planner","parallel","multi-agent","only","execution","plans","dependency","for","multi","implementation",{"skillNo":115,"name":116,"nameZh":6,"description":117,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":118,"categories":119,"keywords":120,"publishedAt":30},"01M6H7ZD93853RZCYQWH1D38TM","super-swarm-spark","Only to be triggered by explicit super-swarm-spark commands.","https:\u002F\u002Fgithub.com\u002F0xharryriddle\u002Fcodex-field-kit\u002Fblob\u002Fmain\u002Fskills\u002Fsuper-swarm-spark\u002FSKILL.md",[],[121,102,122,107,123],"super swarm spark","spark","commands",{"skillNo":125,"name":126,"nameZh":6,"description":127,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":128,"categories":129,"keywords":130,"publishedAt":30},"01M6H7Z987QBY49JCCPT953EAZ","role-creator","Create and install Codex custom agent roles in ~\u002F.codex\u002Fconfig.toml, generate role config files, enforce supported keys, and guide users through required role inputs (model, reasoning effort, developer_instructions).","https:\u002F\u002Fgithub.com\u002F0xharryriddle\u002Fcodex-field-kit\u002Fblob\u002Fmain\u002Fskills\u002Frole-creator\u002FSKILL.md",[],[131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,22,148],"role","creator","role creator","keys","users","roles","toml","enforce","install","guide","instructions","model","developer","reasoning","generate","create","config","files",{"skillNo":150,"name":151,"nameZh":6,"description":152,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":153,"categories":154,"keywords":158,"publishedAt":30},"01M6H7Z5TRPMDQ7YSZQXPN1G60","read-github","Read and search GitHub repository documentation via gitmcp.io MCP service.\n\n**WHEN TO USE:**\n- User provides a GitHub URL\n- User mentions a specific repo in owner\u002Frepo format\n- User asks \"what does this repo do?\", \"read the docs for X repo\", or similar\n- User wants to search code or docs within a repo","https:\u002F\u002Fgithub.com\u002F0xharryriddle\u002Fcodex-field-kit\u002Fblob\u002Fmain\u002Fskills\u002Fread-github\u002FSKILL.md",[155],{"categoryNo":156,"categoryName":157,"taxonomyType":72,"taxonomyTypeDesc":73},"01JBSEEDCAT000000000000023","Skill与智能体开发",[159,160,161,89,162,163,164,165,111,166,167,168,169,170,171,24,172,173,174,175],"github","read github","read","documentation","docs","MCP","search","when to use","URL","via","io","service","do","user","repo","format","repository",{"skillNo":177,"name":104,"nameZh":6,"description":178,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":179,"categories":180,"keywords":181,"publishedAt":30},"01M6H7Z215CTKYJ4Y1X6EQWN6M","Create comprehensive, phased implementation plans with sprints and atomic tasks. Use when user says: \"make a plan\", \"create a plan\", \"plan this out\", \"plan the implementation\", \"help me plan\", \"design a plan\", \"draft a plan\", \"write a plan\", \"outline the steps\", \"break this down into tasks\", \"what's the plan for\", or any similar planning request. Also triggers on explicit \"\u002Fplanner\" or \"\u002Fplan\" commands.","https:\u002F\u002Fgithub.com\u002F0xharryriddle\u002Fcodex-field-kit\u002Fblob\u002Fmain\u002Fskills\u002Fplanner\u002FSKILL.md",[],[104,182,111,183,27,184,82,109,123,185,186,24,187,188,189,190,191,146,80,192],"outline","atomic","sprints","draft","me","write","phased implementation","plan","help","planning","design"]