# SguanFOC: a C library for field-oriented control of brushless motors

> A pure C motor control library that runs a full FOC stack on an MCU, from the coordinate transforms through SVPWM, with nineteen control modes covering open loop, sensored, sensorless and fused operation, four control algorithms and three sensorless observers. The structure is a set of three interrupt-level loops you call from your own timer handlers, and the configuration lives in one header.

**Sguan-ZhouQing/SguanFOC_Library** — SguanFOC为有/无传感器的PMSM电机提供强大的磁场定向控制解决方案。库内集成了基于SVPWM的多种控制模式，支持位置环、速度环、电流环的单环/串级控制...同时针对嵌入式平台优化了数学运算，并提供高度可配置的PID和LADRC等控制器，满足从简单调速到高性能伺服的各类应用需求。

- Repository: https://github.com/Sguan-ZhouQing/SguanFOC_Library
- Stars: 1,107 · Forks: 206
- Language: C
- License: MIT
- Published: 2026-10-19 · Updated: 2026-10-19 · Language: en
- Canonical page: https://hysenlabs.com/projects/sguan-zhouqing-sguanfoc-library

## What the library is, and where it runs

SguanFOC is a high-performance field-oriented control library for PMSM motors, with or without sensors. The repository description says the library integrates several control modes based on SVPWM, supports single-loop and cascaded control of position, speed and current loops, optimises the maths for embedded platforms, and provides highly configurable controllers including PID and LADRC, covering everything from simple speed regulation to high-performance servo applications.

The tagline in the README is the pitch in one line: pure C, a few lines of config, your motor spins like silk.

The platform badge is worth reading precisely, because it defines the scope. It says ARM, DSP, any MCU that supports C. There is no vendor-specific code, no HAL requirement and no build system dependency in the library itself. The cost of that portability is that you supply the platform layer.

The library is MIT licensed, the primary language in the metadata is C, and the repository is not archived with the last push on 2026-10-15. The releases are v3.0.1 from 2026-04-02, 3.0.0 from 2026-03-15 and v2.1 Beta from 2026-03-05. The version badge in the README says 3.1.0, and the repository tree also carries a v4.0.0 directory, so the directory names run ahead of the published tags.

And the README is explicit that the work is not a paper exercise. Every control algorithm it lists has been run on real hardware, and it is not simulation and not a proof of concept.

## The integration model: three loops and your own timer handlers

The whole integration is one header and a set of calls you place in your own interrupt handlers, which is the design decision that makes the library portable.

```c
#include "SguanFOC.h"

int main(void) {
    MCU_Init();
    while(1) {
        SguanFOC_main_Loop();
    }
}

void TIM1_IRQHandler(void) {
    SguanFOC_High_Loop();
}

void TIM2_IRQHandler(void) {
    SguanFOC_Low_Loop();
}
```

The three calls divide the work by frequency, and the comments in the source say what each one is for. The main loop handles initialisation and the serial data send and receive. The high-frequency loop runs the current loop, the angle calculation and the PWM generation, and it goes in your highest priority timer interrupt. The low-frequency loop runs the state machine transitions and the fault protection, and it goes in a lower priority one. A fourth hook, `SguanFOC_Printf_Loop`, handles serial debug reception and parsing.

The consequence for you is that the timing of the control loop is your responsibility, and that is the right trade. A library that owned the timer would be tied to a specific timer peripheral, and the whole point of the split is that you own the hardware and the library owns the maths.

Your own platform work is limited to the `MCU_Init` function, which is yours to write, and to the user configuration headers. The README says that in the `UserData_*.h` files you fill in, in order, the motor control mode and the operating parameters.

## Nineteen modes, four algorithms, three observers

The scale of the feature set is stated as four numbers: nineteen control modes, four control algorithms, three sensorless observers and more than ten advanced features.

The mode table is the clearest view of the design, and it reads as a progression. The first two are open loop, `MODE_VF_OPENLOOP` for voltage to frequency and `MODE_IF_OPENLOOP` for current to frequency, both without a sensor, and both positioned for strong drag and for bench testing with current limiting protection. The third, `MODE_Voltag_OPEN`, is open loop voltage with an encoder, for voltage mode debugging.

Then the sensored single loop and cascades, `MODE_Current_SINGLE` for torque control, `MODE_VelCur_DOUBLE` for general speed control, and `MODE_PosVelCur_THREE` for servo positioning and precision control. Then `MODE_Sensor_Hall`, the Hall sensor speed loop, which the README positions as the low-cost option.

Then the sensorless block, and this is where the observers appear. `MODE_Sensorless_HFI` uses high frequency injection for zero speed running, `MODE_Sensorless_SMO` uses a sliding mode observer for medium and high speed, and `MODE_Sensorless_NLFO` uses a nonlinear flux observer for the same range.

After that come the fused modes, and they are the interesting ones. `MODE_Sensorless_HS` combines HFI with SMO, `MODE_Sensorless_HN` combines HFI with NLFO, `MODE_Sensorless_AS` combines a Hall sensor with SMO, and `MODE_Sensorless_AN` combines a Hall sensor with NLFO. All four are for full speed range with smooth transitions, which is the hard part of sensorless control and the reason a library that implements three observers is worth having.

The last five modes are debug modes, `MODE_Debug_HFI`, `MODE_Debug_SMO`, `MODE_Debug_NLFO`, `MODE_Debug_HS` and `MODE_Debug_HN`, which use an encoder as an external reference for the observer so you can tune the estimator against a known truth.

## Choosing a mode, and the recommendation table

The mode is selected by a macro in `UserData_Config.h`:

```c
#define Define_Run_Mode 11
```

The macro takes a value from 0 to 18, and the README gives a table mapping a need to a recommended mode. If you have just got the motor and want it spinning, use mode 0 or 1, the open loop strong drag modes. For a coil winding machine doing torque control, mode 3, the current single loop. For a balance car or a hub motor, mode 4, the speed and current double loop. For a gimbal, a robot arm, a CNC machine or a 3D printer, mode 5, the position, speed and current triple loop. For a low-cost project with a Hall sensor, mode 6. And for a drone or a high-speed fan, the README's table continues into the sensorless modes.

That mapping is the most useful part of the documentation for a newcomer, because it inverts the problem. Instead of choosing an algorithm and then finding a use for it, you start from the machine you are building and read off the control structure it needs.

The four control algorithms are PID, LADRC, SMC and STA, and the version roadmap shows how they were introduced. The v3.0.0 line, a sensored library with floating point maths, lists PID closed-loop control, an IMC style approach, LADRC linear active disturbance rejection control, MTPA maximum torque per ampere control, feedforward decoupling, a Butterworth filter, printf redirection and the user interface. The v3.0.1 line is the same feature set in Q31 fixed point arithmetic, which is the version for a microcontroller without a fast float unit.

The v3.1.0 line, a sensorless library with floating point maths, adds the HFI injection and rotor position estimation with harmonic suppression, the SMO and NLFO observers, SVPWM and third harmonic injected SPWM, a disturbance observer, field weakening, anti-cogging compensation, dead time compensation, phase delay compensation, rotor polarity identification, motor parameter identification, and the STA super twisting sliding mode controller. The v3.1.1 line is that in fixed point, and the repository tree carries a v4.0.0 directory described as a highly modular and advanced FOC library.

## The sensorless verification, and the defects the README admits

There is a section on the sensorless algorithm verification on real hardware, and it is the most valuable part of the README for anyone considering this library, because it is honest.

There are diagrams of the HFI switching to the SMO, and of the HFI switching to the NLFO, and the notes attached to them are specific. The upper case is high frequency sine injection switching to a sliding mode observer, and the lower case is high frequency injection switching to the nonlinear flux observer. The figures are described as simple parameter verification, with the note that deep tuning gives better results.

And then the sentence that should decide your adoption: the rest of the SguanFOC functions work normally, but the parameter identification and the polarity identification have defects, which a later project will fix.

That is a specific, verifiable limitation, and it matters. Parameter identification is what tells the controller the motor's resistance and inductance, and polarity identification is what establishes which direction the rotor actually turns relative to the current measurement. Both are things you need before a sensorless start-up will work on an unknown motor, and the library tells you those two paths are known to be defective.

The consequences are bounded. If you are bringing up a motor whose parameters you already know, and you are not relying on automatic polarity detection, the defect does not block you. If your plan is to hand the library an unknown motor and let it work it out, the two features you need most are the two that are broken, and you should read the issue tracker before planning around them.

## The repository is a set of libraries, not one library

The top level of the repository is a collection of directories, and that is the first thing to understand about the project. There is a directory for the v3.0.0 sensored floating point library, one for v3.0.1 with Q31 fixed point, one for v3.1.0 sensorless floating point, one for v3.1.1 sensorless fixed point, and one for v4.0.0, described as a highly modular and advanced FOC library.

Then there are three directories that are not code at all. One holds the open hardware, a CH32V3 based robot joint PCB. One holds the companion PC-side GUI and the FOC usage guide as a PDF. And one holds the companion Simulink models, described as the algorithm principle diagrams.

That is a substantial and unusual thing to find in a library repository. The hardware means you can reproduce the author's setup rather than guessing at it, the PC-side tool is the tuning and configuration front end, and the Simulink models are the reference for what the algorithms are supposed to do. For anyone bringing up a motor, the models are the thing that lets you check the implementation against the theory.

The library itself is described as pure C with a small number of configuration lines, and the README states that the MIT licence means it is free for personal and commercial use with no authorisation required, and that it is cross-platform across ARM, DSP and any C-capable MCU.

The release naming also tells you about the trajectory. The tags run v2.1 Beta, then 3.0.0, then v3.0.1, and the newest release is v3.0.1 from April 2026, while the tree already contains v3.1.x and v4.0.0 directories. The development is ahead of the published tags, so the version you install is not the most advanced code in the repository.

## Where SguanFOC is the wrong choice

The first wrong case is a product that needs a safety case. This is a motor control library with a known defect in two of its identification algorithms, a single maintainer, and no qualification story. A servo that moves a load where a runaway would hurt someone needs a control stack with a traceable development process, and a library whose parameter identification is documented as defective is not that.

The second is a team that wants a turnkey motor. The library supplies the control algorithm, the observers and the maths, and it expects you to supply the platform, the timer assignment, the current sensing path and the tuning. That is the right split for an engineer who knows motors, and the wrong split for someone who wants to buy a working servo drive.

The third is a project that needs a sensorless start on an unknown motor without doing the work yourself, because that is precisely the path the README says is defective.

The fourth is a team that needs a supported component with a vendor behind it. The project is a single-maintainer open source library, and the README invites sponsorship rather than offering a support contract.

The fifth is a codebase that cannot live with a macro-driven configuration in a header. Choosing the control mode, the algorithm and the gains happens in `UserData_Config.h` and the related user headers, and a team that wants configuration in a typed, versioned format will be fighting the library's structure.

For the case it is written for, though, this is an unusual amount of working motor control in a form you can read, and the hardware, the model and the tool are all published alongside it.

## Conclusion

SguanFOC suits a hobbyist or engineer bringing up a brushless motor on a microcontroller who wants the whole FOC stack, the observers and the control loops already written, and who is willing to tune gains on real hardware. It does not suit a team that needs a commercial motor control product with a safety certification, and it does not suit anyone who wants a vendor support contract, because the project is a single-maintainer open source library with a self-declared defect in two of its algorithms. Before adopting it, read the section on the sensorless verification, where the README says the parameter identification and polarity identification have known defects that a later project is meant to fix, and confirm your target MCU has the timer and serial peripherals the three loop hooks expect.

## FAQ

### How do I integrate SguanFOC with my microcontroller?

Include `SguanFOC.h`, call `SguanFOC_main_Loop()` in your main loop, `SguanFOC_High_Loop()` in your highest priority timer interrupt for the current loop, angle calculation and PWM generation, `SguanFOC_Low_Loop()` in a lower priority interrupt for the state machine and fault protection, and `SguanFOC_Printf_Loop()` for serial debug reception.

### Which control modes does SguanFOC support?

Nineteen, numbered 0 to 18 and selected with the `Define_Run_Mode` macro in `UserData_Config.h`. They cover open loop voltage and current to frequency, sensored single, double and triple loop control, Hall sensor speed control, three sensorless observers, four fused Hall and observer modes for full speed range, and five debug modes that use an encoder as an external reference.

### What control algorithms and observers does SguanFOC implement?

Four control algorithms, PID, LADRC, SMC and STA, and three sensorless observers, high frequency injection for position estimation, a sliding mode observer and a nonlinear flux observer. It also provides MTPA, field weakening, harmonic suppression, parameter identification, dead time compensation and a Butterworth filter.

### What are the known limitations of SguanFOC?

The README states that the parameter identification and the polarity identification have defects, which a later project will fix, while the rest of the functions work normally. The sensorless figures are also described as simple parameter verification, with better results after deeper tuning.

### Which platforms does SguanFOC support?

ARM, DSP and any microcontroller that supports C, with no vendor-specific dependency in the library itself. The project also publishes the hardware it was developed on, a CH32V3 based robot joint PCB, along with the PC-side tuning tool and Simulink models of the algorithms.

## Sources

- [Issues](https://github.com/Sguan-ZhouQing/SguanFOC_Library/issues)
- [License: MIT](https://github.com/Sguan-ZhouQing/SguanFOC_Library/blob/main/LICENSE)
- [README](https://github.com/Sguan-ZhouQing/SguanFOC_Library/blob/main/README.md)
- [Releases](https://github.com/Sguan-ZhouQing/SguanFOC_Library/releases)
- [Sguan-ZhouQing/SguanFOC_Library on GitHub](https://github.com/Sguan-ZhouQing/SguanFOC_Library)

---

Hysen Labs editorial analysis, written from the project's own repository and release notes. Cite the canonical page: https://hysenlabs.com/projects/sguan-zhouqing-sguanfoc-library
