State Machines

The motor control software uses three distinct state machines operating at different priorities. Understanding their execution context and interaction is essential for customizing or debugging the application.


Execution Architecture

The two main execution contexts are the high-priority ADC ISR and the low-priority background loop in main().

The ADC ISR is triggered by the MCPWM peripheral: each PWM cycle generates an ADC start-of-conversion (SOC) trigger via the PWM XBAR. When the ADC conversion completes, ADC0_INT1_IRQHandler fires. The ISR frequency therefore equals the PWM switching frequency — at the default 15 kHz PWM setting the ISR runs every 66 µs, and the frequency can be scaled up to 100 kHz by increasing USER_M1_PWM_FREQ_kHz in user_mtr1.h and matching the MCPWM period in SysConfig.

digraph execution_arch { rankdir=TB; size="6,9"; node [shape=box, style="filled,rounded", fontname="Helvetica", fontsize=12, margin="0.35,0.18"]; edge [color="#555555", fontname="Helvetica", fontsize=10]; HW [label="MCPWM Hardware\nPWM period end → ADC SOC trigger\n(ISR freq = PWM freq, up to 100 kHz)", fillcolor="#f2f3f4", color="#7f8c8d"]; ISR [label="ADC0_INT1_IRQHandler (isr.c)\nADC conversion complete\nISR period = 1 / USER_M1_PWM_FREQ_kHz ms\n(e.g. 66 µs at 15 kHz, 10 µs at 100 kHz)", fillcolor="#f9ebea", color="#e74c3c"]; APP [label="application_run(&motorVars_M1)\n1. FOC_runFeedback() — read ADC, compute I/V\n2. FOC_runObservers() — FAST / ESMO angle\n3. FOC_runStateMachine() — state transitions\n4. FOC_runFeedforward() — Park, SVPWM output\n5. Data logging", fillcolor="#fdebd0", color="#e67e22"]; BG [label="Background Loop (main.c)\nRuns every ~1 ms\nFOC_runLowPriorityStateMachine()\nFault check, trajectory, monitor", fillcolor="#d5f5e3", color="#27ae60"]; HW -> ISR [label="ADC conversion complete"]; ISR -> APP [label="call application_run()"]; ISR -> ISR [label="timerCntFOCCtrlISR++", style=dashed]; ISR -> BG [label="counter > LOW_PRIORITY_WAIT_TIME_1ms → trigger", style=dashed, color="#27ae60"]; }

The ISR counter timerCntFOCCtrlISR is incremented every ISR tick and checked by the background loop. When it exceeds LOW_PRIORITY_WAIT_TIME_1ms (= 1000 / PWM_kHz ticks), the low-priority state machine runs once and the counter resets.


Startup and Calibration Sequence

Before the motor can run, two calibration phases must complete. Both are initiated in main() before the background loop starts.

digraph startup_cal { rankdir=TB; node [shape=box, style="filled,rounded", fontname="Helvetica", fontsize=10, margin="0.25,0.1"]; edge [color="#555555", fontname="Helvetica", fontsize=9]; A [label="main()\nDevice_Init()\nSYSCFG_DL_init()", fillcolor="#d4e6f1", color="#2980b9"]; B [label="HAL_init() + HAL_setParams()\ninitMotor1Handles()\ninitMotor1CtrlParameters()", fillcolor="#d4e6f1", color="#2980b9"]; C [label="Phase 1: Comparator DAC Offset Cal\nHAL_CompOffsetCalInit()\nBlocking loop: HAL_CompOffsetCalStep()\nSweeps DAC 1800→2400 counts (~2 ms/step)", fillcolor="#fdebd0", color="#e67e22"]; D [label="HAL_RunOffsetCalInit()\nSeeds ADC offsets, enables PWM at 0% duty", fillcolor="#fdebd0", color="#e67e22"]; E [label="motorState = MOTOR_OFFSET_CALIB\nHAL_enableGlobalInts()\nISR now running", fillcolor="#f9ebea", color="#e74c3c"]; F [label="Phase 2: ADC IIR Offset Cal\nISR-driven in MOTOR_OFFSET_CALIB state\nHAL_RunOffsetCalStep() per ISR tick\nRuns for offsetCalibTimeSet_cnt ticks", shape=diamond, fillcolor="#fdebd0", color="#e67e22"]; G [label="motorState = MOTOR_STOP_IDLE\nflagOffsetCalibDone = true\nflagEnableSystem = true", fillcolor="#d5f5e3", color="#27ae60"]; H [label="Background loop starts\nFOC_runLowPriorityStateMachine()", fillcolor="#d5f5e3", color="#27ae60"]; A -> B -> C -> D -> E -> F; F -> G [label="Cal complete"]; G -> H; }

Why Two Calibration Phases?

Phase

Method

What it calibrates

Comparator DAC offset

Blocking sweep before ISR starts

CMPSS DAC trip-point offsets (hardware over-current protection)

ADC IIR offset

ISR-driven, PWM-synchronous

ADC current/voltage channel offsets using IIR filter with live PWM data

The ADC calibration must run with the PWM active (at 0% duty) so that the ADC samples are synchronized to the actual switching noise environment. This is why it runs inside the ISR rather than in a blocking loop.


High-Priority State Machine

FOC_runStateMachine() is called every ISR tick (every PWM cycle). It determines the FOC angle source and current references based on the current motor state.

digraph isr_state_machine { graph [layout=neato, overlap=false, splines=true, size="10,13!", bgcolor="white"]; node [shape=ellipse, style="filled", fontname="Helvetica", fontsize=12, width=1.8, height=0.65, fixedsize=true]; edge [color="#555555", fontname="Helvetica", fontsize=10]; /* ── Main chain: x=3.5, y descends from 12.5 to 0.5 ── */ START [label="Power-on", shape=circle, fillcolor="#f2f3f4", color="#7f8c8d", width=0.9, height=0.9, pos="3.5,12.5!"]; CAL [label="OFFSET\nCALIB", fillcolor="#fdebd0", color="#e67e22", pos="3.5,11!"]; IDLE [label="STOP\nIDLE", fillcolor="#d4e6f1", color="#2980b9", pos="3.5,9.5!"]; SEEK [label="SEEK\nPOS", fillcolor="#d5f5e3", color="#27ae60", pos="3.5,8!"]; ALIGN [label="ALIGN\nMENT", fillcolor="#e8daef", color="#8e44ad", pos="3.5,6.5!"]; IPD [label="IPD", fillcolor="#e8daef", color="#8e44ad", pos="3.5,5!"]; OL_START [label="OL\nSTART", fillcolor="#fdebd0", color="#e67e22", pos="3.5,3.5!"]; OL_END [label="OL\nEND", fillcolor="#fdebd0", color="#e67e22", pos="3.5,2!"]; CTRL_RUN [label="CTRL\nRUN", fillcolor="#d5f5e3", color="#27ae60", pos="3.5,0.5!"]; /* ── Right column outliers ── */ IDENT [label="PARAM\nIDENT", fillcolor="#e8daef", color="#8e44ad", pos="7.5,9.5!"]; FAULT [label="FAULT\nSTOP", fillcolor="#f9ebea", color="#e74c3c", pos="7.5,5!"]; /* ── Invisible waypoint nodes for left-side routing ── */ WP_SEEK [label="", shape=point, width=0.01, style=invis, pos="-0.5,4.25!"]; WP_BACK [label="", shape=point, width=0.01, style=invis, pos="-1.0,5.0!"]; /* ── Main chain forward edges ── */ START -> CAL [label="boot"]; CAL -> IDLE [label="cal done"]; IDLE -> SEEK [label="flying start\nmode"]; SEEK -> ALIGN [label="startup=align"]; SEEK -> IPD [label="startup=IPD"]; IDLE -> ALIGN [label="flagEnableAlignment", style=dashed]; IDLE -> IPD [label="flagEnableIPD", style=dashed]; ALIGN -> OL_START [label="align done"]; IPD -> OL_START [label="IPD done"]; OL_START -> OL_END [label="speed ramp\ncomplete"]; OL_END -> CTRL_RUN [label="observer locked"]; /* ── Skip edge: SEEK → CTRL_RUN via left waypoint ── */ SEEK -> WP_SEEK [label="speed >\nthreshold", color="#27ae60", fontcolor="#27ae60", arrowhead=none]; WP_SEEK -> CTRL_RUN [color="#27ae60", arrowhead=normal]; /* ── Back-edge: CTRL_RUN → IDLE via far-left waypoint ── */ CTRL_RUN -> WP_BACK [label="stop cmd", color="#2980b9", fontcolor="#2980b9", style=dashed, arrowhead=none]; WP_BACK -> IDLE [color="#2980b9", style=dashed, arrowhead=normal]; /* ── Outlier: Parameter ID (right side) ── */ IDLE -> IDENT [label="flagEnableRunAndIdentify"]; IDENT -> IDLE [label="ID complete /\naborted", color="#8e44ad", fontcolor="#8e44ad", style=dashed]; /* ── Fault edges: all go RIGHT to FAULT node ── */ IPD -> FAULT [label="fault", color="#e74c3c", fontcolor="#e74c3c"]; OL_START -> FAULT [label="fault", color="#e74c3c", fontcolor="#e74c3c"]; CTRL_RUN -> FAULT [label="fault", color="#e74c3c", fontcolor="#e74c3c"]; FAULT -> IDLE [label="fault cleared", color="#e74c3c", fontcolor="#e74c3c", style=dashed]; }

State Descriptions

State

Angle Source

Current Reference

Description

MOTOR_OFFSET_CALIB

—

—

ADC IIR offset calibration running in ISR

MOTOR_STOP_IDLE

—

0

Motor stopped, PWM disabled, waiting for command

MOTOR_SEEK_POS

Observer

Flying start logic

Re-synchronize to a spinning motor; exits to CTRL_RUN if speed > threshold, else to ALIGN or IPD

MOTOR_IPD

IPD result

Injection pulses

Initial Position Detection — determines rotor angle at standstill

MOTOR_ALIGNMENT

Fixed angleAlign_rad

alignCurrent_A on d-axis

Force rotor to a known angle before open-loop ramp

MOTOR_OL_START

ANGLE_GEN (ramp)

startCurrent_A on q-axis

Open-loop speed ramp — angle generated internally

MOTOR_OL_END

ANGLE_GEN (ramp)

startCurrent_A

Transition: observer begins tracking open-loop angle

MOTOR_CTRL_RUN

Observer (FAST/ESMO)

Speed PI output

Closed-loop FOC — observer provides angle and speed

MOTOR_PARAM_IDENT

EST angle (FAST)

EST trajectory

InstaSPIN or TiTune parameter identification (outlier)

MOTOR_FAULT_STOP

—

0

Fault active, PWM disabled (outlier)


Low-Priority State Machine

FOC_runLowPriorityStateMachine() runs in the background loop approximately every 1 ms. It handles non-time-critical management tasks: fault checking, stop commands, motor monitoring, and trajectory management.

digraph low_priority_sm { rankdir=TB; node [shape=box, style="filled,rounded", fontname="Helvetica", fontsize=10, margin="0.2,0.08"]; edge [color="#555555", fontname="Helvetica", fontsize=9]; A [label="FOC_runLowPriorityStateMachine()\nCalled every ~1 ms from main()", fillcolor="#d4e6f1", color="#2980b9"]; B [label="LowPriority_handleMotorCheckFaults()\nCheck fault flags, set MOTOR_FAULT_STOP", fillcolor="#fdebd0", color="#e67e22"]; C [label="LowPriority_handleMotorCheckStop()\nProcess stop commands from user", fillcolor="#fdebd0", color="#e67e22"]; D [label="LowPriority_handleCheckInstaSpinEstimatorErrors()\nCheck FAST estimator error flags", fillcolor="#fdebd0", color="#e67e22"]; E [label="LowPriority_handleMotorIDAndTrajectory()\nManage speed trajectory, ID transitions", fillcolor="#fdebd0", color="#e67e22"]; F [label="runMotorMonitor()\nOver-voltage, under-voltage, over-current,\nover-speed, stall detection", fillcolor="#fdebd0", color="#e67e22"]; G [label="motorState?", shape=diamond, fillcolor="#f2f3f4", color="#7f8c8d"]; H [label="resetMotorControl()\nClear PI integrators, reset flags", fillcolor="#d4e6f1", color="#2980b9"]; I [label="Update speed reference trajectory\nApply FWC/MTPA enable flags", fillcolor="#d5f5e3", color="#27ae60"]; J [label="Disable PWM\nWait for fault clear command", fillcolor="#f9ebea", color="#e74c3c"]; K [label="State-specific management", fillcolor="#f2f3f4", color="#7f8c8d"]; A -> B -> C -> D -> E -> F -> G; G -> H [label="MOTOR_STOP_IDLE"]; G -> I [label="MOTOR_CL_RUNNING"]; G -> J [label="MOTOR_FAULT_STOP"]; G -> K [label="Other"]; }

Fault Flags

The FAULT_MTR_BITS structure in motor_common.h tracks all active faults as individual bits in a 16-bit register:

Bit

Fault

Detection

0

overVoltage

DC bus > overVoltageFault_V

1

underVoltage

DC bus < underVoltageFault_V

4

moduleOverCurrent

Hardware CMPSS trip

5

overPeakCurrent

Software current limit

6

overLoad

Torque limit exceeded

7

motorLostPhase

Phase current missing

9

motorStall

Speed = 0 with current applied

10

startupFailed

OL→CL transition failed

11

overSpeed

Speed > overSpeedFault_Hz

12

estimError

FAST estimator error

13

gateDriverFault

Gate driver nFAULT pin


TiTune State Machine

When flagEnableRunAndIdentify is set and motorParamIdentifyMethod == MOTOR_PARAM_IDENTIFY_TITUNE, the motor enters MOTOR_PARAM_IDENT state and StateMachine_handleTiTune() runs TiTune_Run_stateMachine() every ISR tick.

digraph titune_sm { rankdir=TB; size="7,10"; node [shape=box, style="filled,rounded", fontname="Helvetica", fontsize=13, margin="0.35,0.2", width=3.5]; edge [color="#555555", fontname="Helvetica", fontsize=11]; IDLE [label="TiTune_STATE_IDLE", fillcolor="#d4e6f1", color="#2980b9"]; LDQ [label="TiTune_STATE_LDQ_EST\nHF injection at standstill → Ld, Lq", fillcolor="#fdebd0", color="#e67e22"]; RS [label="TiTune_STATE_RS_EST\nDC injection → Rs", fillcolor="#fdebd0", color="#e67e22"]; OL [label="TiTune_STATE_OL_RUN\nOpen-loop speed ramp → Observer lock", fillcolor="#fdebd0", color="#e67e22"]; CL [label="TiTune_STATE_CL_TORQUE_SETTLE\nClosed-loop flux estimation → lambda_PM", fillcolor="#d5f5e3", color="#27ae60"]; INERTIA [label="TiTune_STATE_INERTIA_EST\nCoast-down → J (inertia)", fillcolor="#d5f5e3", color="#27ae60"]; DONE [label="TiTune_STATE_DONE\nTiTune_applyFOCControllers() → Motor stops", fillcolor="#e8daef", color="#8e44ad"]; IDLE -> LDQ [label="flagEnableRunAndIdentify"]; LDQ -> RS [label="Ld/Lq identified"]; RS -> OL [label="Rs identified"]; OL -> CL [label="Observer locked"]; CL -> INERTIA [label="Flux estimation complete"]; INERTIA -> DONE [label="Inertia identified"]; DONE -> IDLE [label="Apply controllers"]; LDQ -> IDLE [label="Fault/abort", style=dashed, color="#e74c3c"]; RS -> IDLE [label="Fault/abort", style=dashed, color="#e74c3c"]; OL -> IDLE [label="Fault/abort", style=dashed, color="#e74c3c"]; CL -> IDLE [label="Fault/abort", style=dashed, color="#e74c3c"]; INERTIA -> IDLE [label="Fault/abort", style=dashed, color="#e74c3c"]; }

TiTune State Descriptions

State

What Runs

Key Output

TiTune_STATE_LDQ_EST

HF voltage injection at standstill

ld_Final, lq_Final

TiTune_STATE_RS_EST

DC current injection, measure voltage drop

Rs_Final

TiTune_STATE_OL_RUN

Open-loop speed ramp to estimation speed

Observer lock

TiTune_STATE_CL_TORQUE_SETTLE

Closed-loop, flux estimation active

lambda_PM (rated flux)

TiTune_STATE_INERTIA_EST

Coast-down frequency sweep

J_Kgm2 (inertia), TiTune_PI_Speed

TiTune_STATE_DONE

TiTune_applyFOCControllers() called

PI gains updated, motor stops

What Happens at TiTune_STATE_DONE

When identification completes, TiTune_applyFOCControllers() in application.h performs the following in sequence:

  1. Writes identified Ld, Lq, Rs, λ_PM into USER_Params

  2. Recomputes Kctrl_Wb_p_kgm2 from identified inertia

  3. Calls setupControllers() to recompute current loop PI gains (Kp = L × BWc, Ki = 0.25 × R/L × T)

  4. Overrides speed PI gains with TiTune_PI_Speed (computed from J/Kt sweep)

  5. Syncs all gains to MOTOR_SetVars_t for watch-window display

  6. Updates observer parameters (FAST or ESMO) with new Rs/Ld/Lq

  7. Returns motor to MOTOR_STOP_IDLE


ISR Execution Budget

The ADC ISR runs at the configured PWM frequency (USER_M1_PWM_FREQ_kHz in user_mtr1.h). The available ISR budget per tick is therefore:

PWM Frequency

ISR Period (budget)

15 kHz (default)

66 µs

20 kHz

50 µs

40 kHz

25 µs

100 kHz (max)

10 µs

The motor control algorithm itself (FOC feedback, observers, state machine, feedforward) consumes approximately 6–10 µs. The remaining budget is available for custom code added to application_run(). At higher PWM frequencies the available margin shrinks significantly — plan custom code accordingly.

The CPU_TIME_Obj (cpuTime) in main.h can be used to measure actual ISR execution time.

Note

The ISR is placed in RAM (.motor_ctrl_ramfunc section) via the MOTOR_CTRL_RAMFUNC attribute to minimize execution latency. Any custom code added to application_run() must also be RAM-resident or fast enough to fit within the available budget for the configured PWM frequency.