In FOC drive control scenarios, prioritize the output of deterministic, mathematically decoupled, and hardware-accelerated C code tailored for hard real-time execution.
First analyze the motor characteristics, sensing topology (1/2/3 Shunt), mechanical sensor presence, and engineering constraints. Then provide implementation recommendations. Never sacrifice inner current-loop bandwidth, synchronization, or fault response time for coding abstraction.
This skill is optimized primarily for STM32G4-class PMSM and BLDC drives. Adapt its recommendations carefully for other MCU families or for motor types whose observer, flux, or slip models differ materially from PM-machine FOC.
If critical runtime context is missing, do NOT assume it away. Ask a concise question that directly changes the implementation path, for example:
Check if the user knows the Motor Parameters ($R_s, L, \Psi$, Pole Pairs). If unknown, you MUST guide the user through the Auto-Tuning process to identify these statically/dynamically before writing arbitrary PID gains.
When a user requests motor drive code or debugging analysis, use the following default path unless the task is clearly narrower (for example review-only, architecture comparison, or a focused bug hunt).
These are the main steps that define the control architecture and the first-pass implementation:
Use these extensions when the product context requires them. They are not separate from the control design, but they do not need to dominate every narrow task:
AI should consult the following domain-specific references when working on the corresponding topics. Fetch files as needed based on the user's request:
When the user starts from a concrete task or symptom and the relevant subset is not obvious, prefer references/problem-oriented-reading-guide.md first so the document load stays focused.
-
references/problem-oriented-reading-guide.md -> First-stop navigation by task or symptom: bring-up, ADC timing, startup failure, braking trouble, thermal issues, host-command problems, resonance, SIL boundaries, and application-specific reading paths.
-
references/auto-tuning-identification.md -> [READ FOR UNKNOWN MOTORS] Stator Resistance ($R_s$), High-frequency Inductance ($L_d, L_q$), Flux Linkage ($\Psi$), Pole Pairs identification, Zero-Pole Cancellation PI tuning, digital delay bandwidth limits.
-
references/emergency-protection-halt.md -> [READ FIRST FOR FAULTS] High-Z coasting vs Active Short Circuit (ASC) decision tree, HardFault handling, STM32G4 BDTR/OISx/OISxN safe-states, Overspeed logic.
-
references/control-foc-loops.md -> Cascaded Loops, PI Feed-Forward with anti-windup, MTPA LUT, Field Weakening voltage-feedback regulator, Bandwidth Rules (10:1 ratio).
-
references/algorithm-svpwm-variants.md -> 7-Segment SVPWM (compact phase-projection and min-max methods), Sector Generation, 5-Segment DPWM constraints, Overmodulation limits, minimum pulse width.
-
references/dq-transform-cordic.md -> Clarke (2-phase KCL optimized), Park, Inverse Park, STM32G4 CORDIC CSR initialization, Async CORDIC ISR pipeline pattern.
-
references/fmac-filtering-and-compensation.md -> When to offload filtering or compensator workloads to STM32G4 FMAC, IIR coefficient loading example, when plain FPU code is better, and what trade-offs must be justified.
-
references/current-sensing-topology.md -> 1-Shunt, 2-Shunt, 3-Shunt timing, Inline sensing, Asymmetric PWM injection, Shunt Resistor ESL, PCB Kelvin connection, RC Anti-aliasing filters, topology selection guide.
-
references/adc-dma-buffering-and-timing.md -> Circular versus ping-pong DMA ownership, ADC sample-packet integrity, compile-time timing guards, and HRTIM as a conditional high-frequency option rather than a default path.
-
references/command-and-supervisory-interfaces.md -> UART/CAN/PWM-input command paths, mode management for torque/speed/position/damping/follow modes, command timeout behavior, target ramping, telemetry, and validation of host-to-motor control behavior.
-
references/can-uart-telemetry-and-diagnostics.md -> Product-grade command framing, telemetry grouping, fault/state reporting, CRC and timeout handling, bus-load limits, and verification of host-visible diagnostics.
-
references/braking-and-regeneration.md -> Normal deceleration versus emergency braking, regenerative versus dissipative energy handling, when the drive behaves as an energy source into the DC bus, brake chopper strategy, source sink-capability constraints, and validation of bus-energy handling.
-
references/power-entry-and-dc-link-management.md -> Power-source assumptions, precharge and inrush control, bus-ready criteria, contactor/relay sequencing, DC-link capacitor stress, brown-in/brown-out behavior, and validation of the power-entry lifecycle.
-
references/gate-driver-and-power-stage-constraints.md -> Gate-driver UVLO/desat behavior, bootstrap edge cases, MOSFET/IPM/SiC/GaN constraints, SOA-aware switching strategy, and fault containment limits at the power-device level.
-
references/emi-emc-isolation-and-cabling.md -> Common-mode current, shielding, grounding, encoder/interface isolation, cable-world dv/dt issues, and practical EMC trade-offs that affect sensing and control reliability.
-
references/production-test-calibration-and-service.md -> Startup self-test, calibration retention, end-of-line checks, service logging, fault injection, and production/field diagnostics expectations.
-
references/safety-architecture-and-diagnostic-coverage.md -> Safety-boundary assumptions, fault layering, watchdog and diagnostic-monitor strategy, latched versus recoverable faults, and expectations for diagnostic coverage and plausibility checks.
-
references/mechanical-integration-and-servo-behavior.md -> Homing, endstops, brake release, gearbox/backlash/compliance effects, resonance-aware servo behavior, and actuator-level validation.
-
references/thermal-system-modeling-and-derating.md -> Winding/module/heatsink thermal paths, sensor-placement validity, thermal time constants, derating law construction, and bench correlation of model versus measured temperature behavior.
-
references/firmware-lifecycle-and-update-strategy.md -> Bootloader/update architecture, rollback policy, protocol/version compatibility, configuration migration, and lifecycle-safe firmware release expectations.
-
references/fault-injection-and-abuse-testing.md -> Deliberate fault injection strategy, electrical/power-stage/sensor/host abuse cases, expected response categories, and acceptance criteria for real failure behavior.
-
references/unit-conventions-and-control-contracts.md -> Mechanical versus electrical frames, peak versus RMS, torque versus current contracts, sign conventions, telemetry naming discipline, and cross-boundary validation rules.
-
references/nvh-and-acoustic-optimization.md -> Audible-noise sources, PWM/dead-time/filtering trade-offs, resonance-aware tuning, and validation of customer-perceived smoothness.
-
references/compliance-and-qualification.md -> Qualification-style disturbance framing, installation and environment assumptions, pass/fail evidence expectations, and firmware-relevant compliance robustness.
-
references/motor-and-load-characterization.md -> Inertia, friction, compliance, resonance, operating-envelope characterization, and why tuning on a free motor is not enough.
-
references/resonance-identification-and-speed-avoidance.md -> Narrow-band vibration diagnosis, electrical/mechanical/order tracking, forbidden-speed and fast-crossing strategies, and resonance mitigation validation.
-
references/compressor-and-refrigeration-drive-applications.md -> Pressure-dependent load behavior, compressor pulsation, correlated pressure/current/vibration logging, and operating-map-based mitigation for refrigeration systems.
-
references/data-logging-replay-and-diagnostics-workflow.md -> Event-triggered snapshots, minimum useful log sets, replay mindset, diagnostic classification, and service-friendly debug workflow expectations.
-
references/commissioning-and-bring-up-playbook.md -> Safe first-power sequence, staged loop enablement, PWM/sensing validation order, common bring-up failure patterns, and what must be proven before moving on.
-
references/configuration-and-parameter-governance.md -> Parameter ownership, variant selection, calibration traceability, corrupted-data handling, and schema/version discipline for real products.
-
references/fan-and-blower-applications.md -> Airflow-related load behavior, startup under restriction, acoustic priorities, and validation of fan/blower-specific operating quality.
-
references/pump-applications.md -> Hydraulic load behavior, startup under head/load, ramp sanity, blocked or abnormal condition handling, and pump-specific validation.
-
references/servo-actuator-applications.md -> Trajectory quality, reversal shock, hold stability, endstop/homing behavior, and actuator-specific validation priorities.
-
references/sil-and-model-based-validation-boundaries.md -> What SIL is good for, what it cannot prove, model-fidelity levels, measured-parameter correlation, and how to distinguish algorithm validation from real physical validation.
-
references/measurement-and-instrumentation-best-practices.md -> Probe selection, grounding pitfalls, timing alignment, DAC/telemetry observability limits, and how to measure drive behavior without fooling yourself.
-
references/common-symptom-to-debug-map.md -> Symptom-driven debug triage, likely fault domains, first measurements to make, and what not to change prematurely.
-
references/sensorless-observers.md -> Sliding Mode Observer (SMO) with sigmoid boundary layer, BEMF extraction, Observer PLL Tracking with correct sign convention, convergence check, High-Frequency Injection (HFI).
-
references/position-sensors.md -> QEP Encoder speed estimation (M/T method), Hall Effect 60-degree angle interpolation and period-based speed, SPI Absolute Encoder delay compensation.
-
references/stm32g4-foc-hardware.md -> Dead-time distortion compensation (parameterized threshold), TIM1 center-aligned PWM initialization, TIM1_TRGO2/CCR4 ADC trigger, Internal OPAMP PGA, COMP→BRK fast trip, ADC dual-regular-simultaneous mode with DMA.
-
references/motor-protection-state-machine.md -> FOC state machine (including TRANSITION state), Startup alignment, Open-Loop V/f ramp, Observer convergence criteria, Bumpless OL→CL transfer, Stall Detection, Catch-spin / flying start, Brake resistor chopper control.
-
references/bldc-six-step.md -> [READ FOR BLDC] Trapezoidal commutation table, Hall→sector→gate mapping, STM32G4 TIM1 COM event, Sensorless BEMF zero-crossing with COMP, Advance angle, Six-step vs. FOC decision guide.
Instead of only outputting static C code, you MUST provide explicit physical verification limits or acceptance criteria for the generated design:
When providing implementation guidance, prefer this response structure unless the user asks for something narrower: