Field-Oriented Control on an ESP32 with SimpleFOC 2.4 and Espressif esp_simplefoc: A Hard Real-Time Timer Loop that Actually Runs

The standard SimpleFOC ESP32 pattern — calling motor.loopFOC() and motor.move() back-to-back inside the Arduino loop() — is a time bomb on a loaded microcontroller. It works beautifully on a bare board with nothing else to do, and then quietly begins to stutter the instant serial commands, sensor reads, communication stacks, or logging start consuming cycles. This article explains the classic ESP32 SimpleFOC pain point, the timer-based hard real-time fix that actually runs, and the safety improvements in SimpleFOC 2.4.0 that make current sensing on the ESP32 more reliable than ever. Everything technical here is attributed to the SimpleFOC and Espressif documentation and the official v2.4.0 release notes, rather than re-tested claims.

Why the naive loopFOC() / move() pattern breaks under load

SimpleFOC is deliberately implemented to be completely cross-platform. As the official documentation explains, the library uses a “generic asynchronous implementation of the FOC loop, where the motor.loopFOC() (field-oriented control runtime) and motor.move() (motion control) functions are called in the main loop of the application as fast as possible.” A typical unoptimised program looks like this:

void loop() {
    // run the FOC algorithm
    motor.loopFOC();
    // run the motion control algorithm
    motor.move();
    // motor monitoring
    motor.monitor();
    // user communication
    command.run();
}

The problem is precisely what the documentation flags: depending on the application, the FOC loop may need to run in “hard real-time, rather than in the main loop where its execution time might be delayed by other code.” Because field-oriented control is a closed-loop algorithm that reads the rotor angle, senses phase currents, and updates the three-phase duty cycles at a fixed cadence, any jitter or missed cycle directly degrades the quality of the current regulation, audible motor noise, and torque smoothness.

On the ESP32 specifically, the main loop() runs as a single FreeRTOS task alongside the WiFi stack, the Bluetooth controller, TCP/IP tasks, and anything else the application schedules. Any of those can preempt the FOC task. The result is the classic symptom set: a motor that hums or whines instead of running smoothly, sporadic torque dips, position drift on position-controlled builds, and intermittent serial lockup. None of it is a hardware fault — it is a scheduling problem.

The clean fix is to stop running the control loop from loop() and instead drive it from a hardware timer interrupt at a fixed frequency. That is the approach both SimpleFOC and Espressif’s own esp_simplefoc component recommend for real-time operation.

The timer-based hard real-time loop on the ESP32

The SimpleFOC documentation provides a canonical ESP32 pattern using the hw_timer API. A one-MHz hardware timer is created, an interrupt-service routine is attached, and an alarm fires the FOC functions every 100 microseconds — a 10 kHz control loop:

#include <SimpleFOC.h>

// ...instantiate the motor, driver, sensor and other components...

hw_timer_t * timer = NULL;

void IRAM_ATTR foc_loop() {
    noInterrupts();          // disable interrupts here
    // call the loopFOC and move functions
    motor.loopFOC();
    motor.move();
    interrupts();            // enable interrupts after
}

void setup() {
    // ...initialise all the components...

    // create a hardware timer, 1MHz resolution
    timer = timerBegin(1000000);
    // attach the interrupt
    timerAttachInterrupt(timer, &foc_loop);
    // set alarm to call foc_loop every 100us (10kHz)
    timerAlarm(timer, 100, true, 0);

    _delay(1000);
}

// the loop now does only monitoring and user communication
void loop() {
    motor.monitor();
    command.run();
}

Two details in this snippet matter for the “actually runs” part. First, the loopFOC() and move() calls are inside an interrupt service routine, which means the rest of the application — communication, monitoring, WiFi, sensors — is completely free to do whatever it likes in loop() without ever delaying the control cadence. That is the entire win: the control loop becomes genuinely hard real-time while the foreground gets the remaining cycles.

Second, the callback is marked IRAM_ATTR. On ESP32, interrupt handlers that run while the flash cache is unavailable (most notably during WiFi transmissions) must have their code located in internal RAM (IRAM). A timer ISR that is not pinned to IRAM can crash or misbehave precisely at the moment the WiFi radio is active — which is exactly when a loaded system is most fragile. The noInterrupts() / interrupts() wrappers around the pair of calls also guard the two-phase operate against nested interrupts.

The frequency warning

The documentation attaches a pointed warning to this approach: “Make sure not to set the timer frequency too high. If the motor.loopFOC() and motor.move() functions take longer to execute than the timer interval, the timer may miss calls or overload the microcontroller. This can cause the motor to malfunction or even crash the microcontroller.” In other words, the timer fixes jitter from other tasks, but it cannot outrun the intrinsic cost of the algorithm itself or of the interferences it enables. Ten kilohertz is the reference figure in the official example; pushing toward 20 kHz or beyond demands measuring the actual ISR execution time and budgeting headroom.

The STM32 parallel

The same strategy exists on STM32, the other microcontroller family the SimpleFOC community uses most heavily. There, the HardwareTimer class creates a timer that calls motor.loopFOC() and motor.move() at a fixed rate — for instance a 10 kHz timer on TIM5. The documentation’s guidance is to avoid reusing a timer occupied by the PWM driver or the position sensor; on STM32 the timers consumed by PWM are printed to the serial monitor by motor.init() and are also listed in the per-family pinout docs. The ESP32 has no such dedicated-timer conflict because PWM duty is produced by the LEDC/MCPWM peripherals rather than by timers the ISR would otherwise share.

A second, complementary path: Espressif’s esp_simplefoc component

For developers building on the ESP-IDF framework rather than Arduino, Espressif ships an official companion: the esp_simplefoc component, described in its documentation as “an FOC component based on Arduino-FOC, developed specifically for ESP chips that support LEDC and MCPWM functions.” Its documented feature set is notable for an ESP32-focused project:

  • Voltage control support.
  • Motor parameters configurable through SimpleFOCStudio.
  • Compatibility with Arduino-FOC control routines and API — the API interface is consistent with Arduino-FOC, so code and lessons transfer between the two ecosystems.
  • IQMath for FOC computation acceleration — Espressif’s fixed-point math library is applied to speed up the FOC math.
  • Manual selection of LEDC or MCPWM peripherals, supporting control of up to four brushless motors from a single device.

The component is added to an ESP-IDF project with a single command:

idf.py add-dependency "espressif/esp_simplefoc"

Hardware parameters — pole-pair count, phase resistance R, KV, and inductance L (all defaulting to NOT_SET until configured), the PWM and enable pins, supply and limit voltages, and the angle sensor — are all set in code, with the documented example initialising an AS5600 over I2C for a 14-pole-pair motor on a 3PWM, 12 V driver. The component’s own reference loop still runs motor.loopFOC() and motor.move() in a foreground while(1) block, which is why the real-time-timer discussion above applies equally to those builds.

The FreeRTOS tick-rate requirement

One ESP-IDF-specific configuration detail is easy to miss and worth flagging: the component documentation instructs you to raise the FreeRTOS tick rate. Under idf.py menuconfig, navigating to Component config → FreeRTOS → Kernel, the configTICK_RATE_HZ value defaults to 100. The documentation states plainly that in FOC scenarios it “needs to be set to 1000.”

The reason follows from the previous section: a 100 Hz tick cannot schedule or preempt tasks with anywhere near the granularity a 1 kHz control-rate application expects, and higher-rate FOC calls built on top of FreeRTOS timing inherit that coarse granularity. Bumping the tick to 1 kHz keeps RTOS delays, task delays, and any FreeRTOS-timer-based scheduling aligned with the sub-millisecond pacing the motor actually needs. This is a configuration step, not a code change, which is exactly the sort of thing that silently undermines a build that looks correct.

IRAM considerations for esp_simplefoc

The IRAM discipline from the Arduino timer example carries over to ESP-IDF builds. Because the interrupt handler must execute even when the flash cache is unavailable (the WiFi-connected case that defines most real ESP32 products), the FOC ISR and the code it calls should live in IRAM. The Arduino-side IRAM_ATTR on the foc_loop callback in SimpleFOC’s real-time-loop guide is the canonical illustration of this requirement, and ESP-IDF offers the equivalent attribute plus menuconfig options for placing interrupt handlers in internal RAM. A motor build that omits this step can appear stable over USB and then fault when network traffic is present.

SimpleFOC 2.4.0: ESP32 safety and current-sense improvements

SimpleFOC 2.4.0, released February 19, 2026, is the release that finally makes the ESP32 the comfortable home for FOC that the hardware always wanted to be. The official release record lists a cluster of ESP32-specific fixes and features worth knowing about because they directly affect how reliably the timer loop above performs:

  • Many ESP32 safety optimisations by @uLipe (pull requests #490–#495). These are the changes that turn an ESP32 FOC build from “works on the bench, occasionally jitters” into something safe to leave running.
  • Better ADC–Timer alignment for more stable current sensing, with a referenced upstream commit. Current sensing is only as good as the moment the ADC samples relative to the PWM cycle; better alignment means cleaner phase-current measurements, which the FOC loop feeds directly into its torque estimates.
  • Compilation across all v3.x arduino-esp32 releases. The release notes state that v2.4.0 “now compiles for all v3.x arduino-esp32 versions” where v2.3.5 was only compatible with v3.2.x. For anyone who has fought version drift between the Arduino-ESP32 core and SimpleFOC, this is the compatibility story that removes the pain.
  • adcRead refactor. The analog read path was cleaned up “so no more magic numbers,” making porting and tuning on ESP32 current sensing more transparent.

The release also adds features that change how a motor build is wired, not just how it runs:

  • Current and voltage feed-forward terms added to the motor classes by @Copper280z (pull request #454), improving tracking performance by supplying feed-forward signal alongside the feedback controller.
  • estimated_current torque control mode, a model-based current-estimation mode for builds without dedicated current sensing.
  • A new align_current_sense.ino example added under examples/utils/current_sense_test, for verifying alignment between the driver and the current-sense phases.

The current-sense alignment example deserves emphasis because it ties directly to production reliability. SimpleFOC’s FOC algorithm assumes the measured phase currents correspond to the correct PWM phases; a sensor wired out of phase produces stable-looking but physically wrong torque. The new example is the verification harness for that alignment, and combined with the ADC–timer alignment work it addresses the two main ways ESP32 current sensing historically went subtly wrong.

Hardware and firmware matrix

The board-and-core matrix below summarises the configuration that the documentation supports, alongside the gotchas most likely to trip up a build.

ESP32 board / core Recommended config Gotchas
ESP32 (classic, dual-core) — Arduino framework SimpleFOC 2.4.0; run loopFOC()/move() in a 10 kHz hw_timer ISR; mark callback IRAM_ATTR Do not raise the ISR rate unless the ISR execution time is budgeted — the docs warn a too-fast timer can miss calls or crash the MCU. Pin the ISR to IRAM or it faults during WiFi traffic.
ESP32 with Arduino-ESP32 core v3.x SimpleFOC 2.4.0 (compiles across all v3.x releases; v2.3.5 only matched v3.2.x) Version drift between the core and SimpleFOC caused earlier breakage; pin both to tested versions before production.
ESP32 — ESP-IDF project Install espressif/esp_simplefoc via idf.py add-dependency; select LEDC or MCPWM; set configTICK_RATE_HZ to 1000 under FreeRTOS Kernel Forgetting the tick-rate change (defaults to 100 Hz) leaves scheduling too coarse for FOC. Place the control ISR in IRAM for WiFi-connected builds.
ESP32 motor driver + current sense Align ADC sampling with the PWM phase; verify phase-to-sense mapping using the new align_current_sense.ino example Mismatched current-sense phase and driver phase yields stable but wrong torque; ADC–timer misalignment adds noise to phase-current readings.
STM32 (comparison) Use HardwareTimer (e.g. 10 kHz on TIM5) to drive loopFOC() and move() Avoid timer conflict with the PWM driver or position sensor; the timers used by motor.init() are printed to serial to help you pick an idle timer.

A written, load-tested, documented path forward

Pulling the threads together, the path to an ESP32 SimpleFOC build that keeps its control cadence under a full application load is a small, well-documented set of decisions:

  1. Move the control loop out of loop(). Drive motor.loopFOC() and motor.move() from a hardware timer ISR at a fixed rate — the 10 kHz reference in the SimpleFOC real-time-loop guide — rather than hoping the main loop stays lean enough to schedule them on time.
  2. Keep the ISR in IRAM on the ESP32 so it runs even when the flash cache is unavailable, and wrap the pair in noInterrupts() / interrupts(). Budget the ISR execution time and do not set the timer interval shorter than the algorithm can actually complete.
  3. If you are on ESP-IDF, use Espressif’s esp_simplefoc component for its IQMath acceleration, LEDC/MCPWM selection, SimpleFOCStudio configurability, and multi-motor support — and remember to raise configTICK_RATE_HZ to 1000.
  4. Build on SimpleFOC 2.4.0 for the ESP32 safety optimisations, the across-the-board Arduino-ESP32 v3.x compatibility, and the ADC–timer alignment work. Validate your current-sense wiring with the new align_current_sense.ino example before expecting trustworthy torque.

The realism necessary for this to work is worth restating plainly: a timer does not eliminate the cost of the FOC algorithm, it eliminates the jitter other code injects into the algorithm’s execution time. Kept honest about that limit, the timer ISR approach — in either the Arduino hw_timer form documented by SimpleFOC or the ESP-IDF esp_simplefoc component documented by Espressif — is the difference between a motor at the mercy of a scheduler and a motor that runs to its schedule.


Primary sources: SimpleFOC — Real-time loop (hard real-time FOC loop using timers), docs.simplefoc.com/real_time_loop; Espressif — ESP SimpleFOC, ESP-IoT-Solution latest and release-v2.0; SimpleFOC v2.4.0 release record, Zenodo, zenodo.org/records/18698344.

Hardware used in this guide

Links open search results on Amazon.in. As an Amazon Associate we earn from qualifying purchases.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top