Skip to content

MCLib and motor control

MCLib is the motor control library of the FlashForge Creator 5 and Creator 5 Pro: the part of the mainboard firmware (mainBoardGD, a GigaDevice GD32H737) that drives the X, Y and Z motors as closed-loop steppers with field-oriented control (FOC). FlashForge doesn't document it, and GigaDevice publishes nothing on it either. This page, and the pages it links to, describe how it works and how OpenCreator's open-source replacement differs.

On top of what the stock library does, OpenCreator's MCLib adds:

  • VFA correction per motor: tables for the 1, 2, 4, 6 and 8 times per motor cycle ripples, sent ahead of the current loop's lag, calibrated with the accelerometer at the speeds where each motor vibrates most. See VFA compensation.
  • Quieter motion: step interpolation, current feedforward and adjustable current loop bandwidth. See Quieter motors.
  • Stall and slip detection from the observer's angle error (below).

The mainboard chip

From GigaDevice's GD32H737xx Datasheet (Rev 2.1), for the GD32H737VGT6 on the mainboard:

Core Arm Cortex-M7, up to 600 MHz
Memory 1024 KB flash, 1024 KB SRAM
Package LQFP100, 78 GPIO
Motor PWM X on TIMER3 (16-bit general timer), Y on TIMER7 (16-bit advanced timer, the one meant for motor control PWM), Z on TIMER1 (32-bit general timer)
Current sensing The two 14-bit ADCs (4 MSPS), ADC0 and ADC1, read by injected channels and DMA, triggered by TIMER2 and TIMER4 (the third ADC, ADC2, is the 12-bit one)
Timestamps TIMER22, a free-running 32-bit timer

The timer and ADC assignments are the ones Kalico's src/stm32/c5_mainboardgd.c sets up; the board's wiring decides which pins each motor's PWM and current sense use.

The X, Y and Z motors are not driven by stepper driver chips. The GD32 mainboard drives each motor's two windings directly from its timer channels, and shapes the current itself. On stock firmware that shaping is FlashForge/GigaDevice's closed-source MCLib motor control library, part of the stock mainboard firmware. Kalico ships a clean-room replacement for it, written from observing what the stock library does; the G-code commands keep their MCLIB_* names so existing config works.

What MCLib replaces

Klipper normally tells a stepper driver "one step" and the chip handles the rest. Here there is no driver chip between the MCU and the motor coils:

Driver-chip Klipper Creator 5 mainboard
Steps Driver chip microsteps internally MCU generates the winding current waveforms
Current limit Set by driver config Closed-loop, controlled by firmware
Feedback Usually none Phase currents read back by ADC at 20 kHz
Lost steps Invisible Detectable in ours: the angle error is measured continuously

So the step pins the config lists for X, Y and Z (PJ0–PJ11) are not real GPIO. c5_mainboardgd_gpio.c maps them to virtual pins: writing X_STEP calls c5_mclib_step(), which advances the motor's electrical angle by one microstep; X_DIR sets the direction; X_EN enables or disables the winding drive; and reading X_ENDSTOP (PJ3/PJ7) actually returns the MCLib stall flag for that axis. Klipper's normal motion planning, homing and endstop logic all work unchanged on top of this.

The extruder is not MCLib: it lives on the eBoard behind a TMC2209, as described in MCU development. Kalico's replacement only covers the three mainboard motors.

The control loop

flowchart TD
  subgraph host["Klipper host"]
    A[step queue]
  end
  subgraph mcu["GD32 mainboard"]
    B[virtual step pin<br/>advances electrical angle] --> C[20 kHz control loop]
    D[ADC phase currents] --> C
    C --> E[PI controllers<br/>+ observer estimates angle]
    E --> F[PWM compare values]
    F --> G[3 motor half-bridges]
    G --> H[motor coils]
    H --> D
  end
  A -->|serial| B

At about 20 kHz (one control period is 50 µs), per motor:

  1. Two ADC channels read the winding currents (ia, ib). The samples arrive by DMA into non-cached memory; a 2000-sample average first establishes the zero-current offset of each channel.
  2. An observer (a current observer with high-frequency injection) estimates the motor's real electrical angle from the current history.
  3. The estimated angle and the commanded angle (from the step pin) are compared. The error drives current PI controllers in the rotating d/q reference frame; the outputs go through an inverse transform back to per-winding voltages.
  4. The voltages become PWM compare values for the motor's timer, which drives the half-bridges.

Between steps, interpolate moves the commanded angle linearly to the next step's scheduled time (the step interpolation in Quieter motors). Each step is timed from its scheduled clock, not from when the timer interrupt got to it. When steps stop arriving for a while the motor drops to hold_current on a ramp; the currents decay to zero when disabled.

X and Y switch to a high-speed mode above a step-rate threshold (about 560 mm/s of belt travel): the speed controller takes over from the current controllers and no VFA correction is applied there. Leaving it starts both current PIs from the voltage the high-speed mode was applying, so the output carries on instead of jumping. The crossover, the stock damping cutoff and the slow-speed threshold follow the configured microsteps, so they stay at the same motor speeds at 32 or 64 microsteps.

Timing

Kalico's notes record, on a Creator 5 Pro with fast X/Y moves at 600 mm/s, about 2,800 CPU cycles per control update on X, 2,400 on Y and 1,500 on Z, so the three motors use about a fifth of each control period. The longest update measured 9 µs, the longest gap between updates 53 µs, and no update came late. MCLIB_TIMING STEPPER=... reports these figures on your printer.

To get there, the control path (the motor interrupts and everything they call) runs from RAM (C5_FAST, the .ramfunc section); from flash, an update whose code had dropped out of the cache took up to 28 µs. The firmware is built for the hard-float ABI, about 5% faster than softfp. With firmware that declares C5_MAINBOARD_STEP_BOTH_EDGE, [mclib] asks for step-on-both-edges, so a step is one timer event instead of a step and an unstep. Host and firmware need to match.

Configuring it

Each motor has a [mclib stepper_*] section next to its normal [stepper_*] in printer.base.cfg. Kalico sends it to the mainboard at connect time:

[mclib stepper_x]
motor_rs: 1.7     # winding resistance, ohm
motor_ls: 0.0026  # winding inductance, H
motor_km: 0.1729  # torque / back-EMF constant
bus_voltage: 24.0
run_current: 1.8
hold_current: 1.5
interpolate: True

The motor parameters set the PI gains and the observer model, so they need to match the real motor (the BJ42D29-30V22/V23 values are in printer.base.cfg). Other options:

Option Default What it does
stall_threshold the bus voltage Torque below which a running motor counts as stalled
current_bandwidth 100 Scales the current PI gains in percent of stock (100 = about 1 kHz), from 25 to 400
feedforward 0 Adds the voltage back-EMF and inductance need up front, from the commanded speed (X and Y; Z ignores it)
step_error Kalico's 25 µs How early a compressed step may come; less makes the step times the interpolation follows more exact
td1_*, td2_*, td4_* 0 The stock VFA damping values (amplitude and a phase per direction)
vfa_1 … vfa_8 OpenCreator's VFA correction tables, written by calibration
vfa_delay 75 µs How far ahead of the current loop the correction runs

Runtime commands: MCLIB_SET_CURRENT changes the currents, MCLIB_SET_STALL the stall threshold, MCLIB_SET_BANDWIDTH and MCLIB_SET_FEEDFORWARD the current loop, MCLIB_TIMING reports loop timing and current noise, MCLIB_SLIP_LOG the slip counter, and MCLIB_SET_RESONANCE_DAMP / MCLIB_APPLY_CALIBRATION / MCLIB_SET_RIPPLE drive the VFA compensation tables. Values found by calibration are saved back into these sections by SAVE_CONFIG.

VFA correction

The mainboard takes one correction per electrical harmonic off the d-axis current, per direction of travel. A vfa_<k> table holds groups of electrical frequency, then amplitude and phase forward, then amplitude and phase in reverse, up to six points per harmonic. A table replaces the stock damping for that harmonic at every speed; harmonics 1, 2 and 4 without a table fall back to the stock td1/td2/td4 values.

A table holds the current the motor should get. The current loop lags behind its command, more so the faster the ripple, so the mainboard multiplies each table value by the loop's inverse response for that frequency (capped at 2.24 times) and runs the angle vfa_delay ahead. Because the lag is taken out, a table's end values hold past either end, so corrections measured up to 150 mm/s keep working at travel speeds. Tables saved as ripple_<k> by earlier versions had the lag inside; they're ignored, and [mclib] raises a warning (vfa_recalibrate: True in its status) until you calibrate again.

Calibration

VFA_MOTORS (the VFA button) calls MCLIB_RIPPLE_CALIBRATE from Kalico's mclib_ripple.py for each motor:

  1. Quick sweep. With the harmonics being calibrated set to no correction, it measures 20 speeds spread on a log scale over 10 to 150 mm/s and picks up to 6 where the motor vibrates most, kept apart on a log scale.
  2. Per speed. At each picked speed it measures all harmonics at once (each vibrates at its own frequency), probes every harmonic's response and computes the correction that cancels it, then refines it. Measurements are coherent: each pass starts at the same motor angle, so the motor's own vibration adds up and everything else averages out. Harmonics above 40% of the accelerometer's sample rate aren't measured.
  3. Current loop delay. A delay the mainboard doesn't run ahead of shows as corrections rotating with speed. It fits the delay (0 to 400 µs) that makes each harmonic's corrections agree best across speeds.
  4. Keep check. The new correction, the old one and no correction are measured alternately (1x and 2x at the calibrated speeds, 4x to 8x over the 20-speed sweep), and each harmonic and direction keeps whichever wins both times, judged only where its frequency is 20 Hz or more.

The step-by-step user view, and measured results, are on VFA compensation and Quieter motors. VFA_MOTORS GRAPH=1 also sweeps before and after and draws the result to config/vfa/vfa_<stepper>.png with vfa_graph.py.

The stock calibration code is still there as stepper_resonance_tester.py (STEPPER_RESONANCE_* commands), with OpenCreator's fixes, for the td1/td2/td4 values. See The stock damping calibration.

Stall and slip detection

Added by OpenCreator

Stock MCLib reports nothing; the observer's angle error is there for the control, but stock never watches it. This detection, and the guard below, are OpenCreator additions built on our replacement.

Because the observer measures the real angle, the mainboard can tell when the motor isn't where it commanded it to be:

  • Stall: filtered torque drops below stall_threshold while the motor is running (armed after 17 quarter-steps of motion, and off during hold transitions and slow motion). Reads as the axis "endstop" pin.
  • Slip: the angle error drifts by whole electrical cycles (one cycle = four full steps, 0.8 mm on X/Y), counted with hysteresis while moving.

At low speed and standstill the back-EMF the observer relies on is close to zero, so below the high-speed mode the firmware learns the standstill part of the error, follows the angle only while the signal is strong enough, and lets small drift fade with a 1 s time constant. A real slip takes a few tens of milliseconds, so it still counts.

The optional [c5_motion_guard] (off by default) polls these counters twice a second over a print, ignores homing and toolchange windows, and warns or pauses when an axis loses steps (C5_MOTION_STATUS shows them). It needs mainboard firmware with the mclib_query_status command. Prints watch slips in fast moves only; slip_watch: holding or always widen that in test mode. See Motion guard.

Source and firmware

The replacement is the portable core in src/c5_mclib.c (no hardware registers, unit-tested in test/c5_mclib.c) plus the hardware layer in src/stm32/c5_mainboardgd.c that sets up the timers, ADCs and DMA. On the host, klippy/extras/mclib.py (which started from GigaDevice's own host module) sends each [mclib stepper_*] section and registers the MCLIB_* commands; mclib_ripple.py measures and calibrates the ripple; c5_motion_guard.py is the motion guard.

scripts/build_c5_update.py builds the four board firmwares into stock update packages, and validates that the mainboard build contains the config_mclib command family and none of the commands the stock library used (mclib_set_pid_params, mclib_identify_motor, ...), so a half-updated board fails the build instead of the printer. How the firmware gets onto the boards is on Firmware, installer and updates.

CPU faults are caught by c5_mainboardgd_fault.c, which turns the motor PWM outputs off before reporting; an unhandled fault would otherwise leave the windings energised.