Motor Data Structures

The motor control software uses a layered set of data structures. Understanding how data flows from static motor nameplate parameters through to live runtime control variables is essential for tuning, debugging, and extending the application.


Data Flow Overview

digraph data_flow { rankdir=LR; node [shape=box, style="filled,rounded", fontname="Helvetica", fontsize=10, margin="0.2,0.1"]; edge [color="#555555", fontname="Helvetica", fontsize=8]; A [label="Motor_ParamsType\nmotor_params.c\nNameplate constants\n(Rs, Ld, Lq, flux, poles)", fillcolor="#d4e6f1", color="#2980b9"]; B [label="USER_Params\nuserParams_M1\nAlgorithm config\n(PWM freq, ISR ticks,\nsense gains, PI gains)", fillcolor="#d5f5e3", color="#27ae60"]; C [label="PI Controllers\npi_Id, pi_Iq, pi_spd\nInside MOTOR_Vars_t", fillcolor="#d5f5e3", color="#27ae60"]; D [label="MOTOR_SetVars_t\nmotorSetVars_M1\nRuntime setpoints\n(startCurrent, alignCurrent,\nfault thresholds, PI gains)", fillcolor="#fdebd0", color="#e67e22"]; E [label="MOTOR_Vars_t\nmotorVars_M1\nMaster motor object\n(all handles + live state)", fillcolor="#f9ebea", color="#e74c3c"]; F [label="MOTOR_InputCtrl_t\nUser commands\n(speedRef_Hz, flagEnableRun,\nestimatorMode, flagEnableFWC)", fillcolor="#e8daef", color="#8e44ad"]; G [label="MOTOR_OutVars_t\nFOC outputs\n(motorState, angleFOC_rad,\nVdq_out_V, speed_Hz)", fillcolor="#f2f3f4", color="#7f8c8d"]; H [label="MOTOR_StatusVars_t\nInternal status\n(angleEST_rad, speedPLL_Hz,\nenableSpeedCtrl, faultMtrNow)", fillcolor="#f2f3f4", color="#7f8c8d"]; I [label="HAL_FOC_Data_Obj\nHW interface data\n(adcData, pwmData,\ngdDataHandle, compOffsetData)", fillcolor="#fdebd0", color="#e67e22"]; A -> B [label="initMotor1CtrlParameters()"]; B -> C [label="setupControllers()"]; B -> D [label="initMotor1CtrlParameters()"]; D -> E [label="read by"]; C -> E [label="inside"]; F -> E [label="written by user\nread by ISR"]; E -> G; E -> H; E -> I [label="via halInterface"]; I -> G [label="adcData →\nIdq, Vdc"]; I -> G [label="pwmData →\nVabc_pu"]; }


Primary Structures

Motor_ParamsType — Motor Nameplate Data

File: motor_params.h, motor_params.c

This is the source of truth for motor electrical and mechanical parameters. It is a const table — one entry per supported motor. The active motor is selected by the motorParams_M1 pointer in motor_params.c.

Field

Unit

Description

NumPolePairs

—

Number of pole pairs

Rs_Ohm

Ω

Phase resistance

Ls_d_H

H

D-axis inductance

Ls_q_H

H

Q-axis inductance

RatedFlux_VpHz

V/Hz

Rated flux linkage

RatedCurrent_A

A

Rated phase current

Inertia_Kgm2

kg·m²

Rotor inertia

RatedSpeed_Hz

Hz

Rated electrical speed

OlSpeedThr_Hz

Hz

Open-loop → closed-loop transition speed

OlTorqueCurrent_A

A

Open-loop torque current

AlignCurrent_A

A

Rotor alignment current

EsmoKslideMax/Min

—

ESMO sliding mode gain range

EsmoPllKpMax/Min

—

ESMO PLL proportional gain range

EsmoPllKi

—

ESMO PLL integral gain

To add a new motor, add a new Motor_ParamsType constant in motor_params.c and update the motorParams_M1 pointer:

/* motor_params.c */
const Motor_ParamsType Motor_myNewMotor = {
    .NumPolePairs    = 4,
    .Rs_Ohm          = 0.85f,
    .Ls_d_H          = 0.00135f,
    .Ls_q_H          = 0.00135f,
    .RatedFlux_VpHz  = 0.0415f,
    /* ... */
};

/* Set active motor */
const Motor_ParamsType *motorParams_M1 = &Motor_myNewMotor;

USER_Params — Algorithm Configuration

File: userParams.h (SDK), populated from user_mtr1.h

USER_Params holds the algorithm-level configuration derived from board constants in user_mtr1.h. It is computed once at init by initMotor1CtrlParameters() and is read-only during operation.

Key fields populated from user_mtr1.h macros:

USER_Params Field

Source Macro

Description

ctrlFreq_Hz

USER_M1_ISR_FREQ_Hz

ISR / control loop frequency

numCtrlTicksPerSpeedTick

USER_M1_NUM_ISR_TICKS_PER_SPEED_TICK

Speed controller decimation

motor_numPolePairs

Motor_ParamsType.NumPolePairs

Pole pairs

motor_Rs_Ohm

Motor_ParamsType.Rs_Ohm

Stator resistance

motor_Ls_d_H

Motor_ParamsType.Ls_d_H

D-axis inductance

motor_Ls_q_H

Motor_ParamsType.Ls_q_H

Q-axis inductance

motor_ratedFlux_Wb

Computed from RatedFlux_VpHz

Rated flux in Webers

maxFrequency_Hz

USER_M1_MOTOR_MAX_SPEED_Hz

Maximum electrical speed

Kctrl_Wb_p_kgm2

Computed from Inertia_Kgm2

Speed loop gain factor


MOTOR_SetVars_t — Runtime Setpoints

File: motor_common.h (global: motorSetVars_M1)

MOTOR_SetVars_t holds the runtime-adjustable setpoints and thresholds. These are initialized from Motor_ParamsType and user_mtr1.h at startup, but can be modified at runtime via the watch window for tuning.

Key field groups:

Group

Key Fields

Description

Motor parameters

Rs_Ohm, Ls_d_H, Ls_q_H, flux_Wb

Electrical params (updated by TiTune)

PI gains

Kp_Id, Ki_Id, Kp_Iq, Ki_Iq, Kp_spd, Ki_spd

Controller gains (updated by TiTune)

Current limits

startCurrent_A, alignCurrent_A, maxCurrent_A

Operating current limits

Speed limits

olSpeedThr, accelerationMax_Hzps, accelerationStart_Hzps

Speed ramp parameters

Fault thresholds

overVoltageFault_V, underVoltageFault_V, overCurrent_A

Protection limits

Timing counts

alignTimeDelay_cnt, offsetCalibTimeSet_cnt

State timing in ISR ticks

Note

After TiTune completes, TiTune_applyFOCControllers() writes the identified motor parameters and recomputed PI gains back into MOTOR_SetVars_t so they are visible in the watch window.


MOTOR_InputCtrl_t — User Commands

File: motor_common.h (field inside MOTOR_Vars_t: motorVars_M1.inputCtrl)

MOTOR_InputCtrl_t is the user-facing command interface. These fields are written by the user (via watch window, UART command, or host interface) and read by the ISR state machine and speed controller.

Field

Type

Description

flagEnableRunAndIdentify

bool

Set true to start motor (or start identification)

flagClearFaults

bool

Pulse true to clear active faults

speedRef_Hz

float32_t

Speed setpoint in electrical Hz

direction

float32_t

1.0f = forward, -1.0f = reverse

estimatorMode

ESTIMATOR_Mode_e

ESTIMATOR_MODE_FAST or ESTIMATOR_MODE_ESMO

motorParamIdentifyMethod

MotorParamIdentify_Method_e

INSTASPIN or TITUNE

flagEnableFWC

bool

Enable field weakening control

flagEnableMTPA

bool

Enable maximum torque per ampere

flagEnableDTC

bool

Enable dead-time compensation

startupMode

STARTUP_Mode_e

STARTUP_ALIGN, STARTUP_IPD, STARTUP_FREE

operateMode

OPERATE_Mode_e

Speed control or torque control

Typical Motor Start Sequence (Watch Window)

/* 1. Set speed reference */
motorVars_M1.inputCtrl.speedRef_Hz = 50.0f;
motorVars_M1.inputCtrl.direction   = 1.0f;

/* 2. Select estimator */
motorVars_M1.inputCtrl.estimatorMode = ESTIMATOR_MODE_ESMO;

/* 3. Enable run */
motorVars_M1.inputCtrl.flagEnableRunAndIdentify = true;

MOTOR_OutVars_t — FOC Outputs

File: motor_common.h (field inside MOTOR_Vars_t: motorVars_M1.outVars)

MOTOR_OutVars_t contains the primary outputs of the FOC algorithm — the values that are written by the ISR and read by the background loop for monitoring.

Field

Unit

Description

motorState

MOTOR_State_e

Current state machine state

angleFOC_rad

rad

FOC angle used for Park/iPark transforms

Idq_in_A

A

Measured d-q currents (after Park transform)

Idq_out_A

A

Current references (d-axis: FWC/MTPA, q-axis: speed PI)

Vdq_out_V

V

Voltage commands from current PI controllers

Vab_out_V

V

Alpha-beta voltage commands (after iPark)

speed_Hz

Hz

Estimated electrical speed

faultMtrNow

FAULT_MTR_REG_t

Active fault flags (bit field)


MOTOR_StatusVars_t — Internal Status

File: motor_common.h (field inside MOTOR_Vars_t: motorVars_M1.statusVars)

MOTOR_StatusVars_t holds internal algorithm state — intermediate values used by the FOC algorithm that are useful for debugging but not directly commanded by the user.

Field

Unit

Description

angleEST_rad

rad

FAST estimator angle (with delay compensation)

anglePLL_rad

rad

ESMO PLL angle (with delay compensation)

angleObs_rad

rad

Active observer angle (FAST or ESMO, selected by estimatorMode)

speedEST_Hz

Hz

FAST estimator speed

speedPLL_Hz

Hz

ESMO PLL speed

speedAbs_Hz

Hz

Absolute speed (used for fault detection)

speed_int_Hz

Hz

Speed trajectory integrator output

enableSpeedCtrl

bool

Speed controller enable (managed by state machine)

enableCurrentCtrl

bool

Current controller enable

offsetCalibTimeCnt

—

ADC offset calibration tick counter

stateRunTimeCnt

—

Time-in-state counter (used for state transitions)


MOTOR_Vars_t — Master Motor Object

File: motor_common.h (global: motorVars_M1)

MOTOR_Vars_t is the top-level motor control object. It contains all sub-structures and handles as fields. The ISR receives a MOTOR_Handle (pointer to MOTOR_Vars_t) and accesses everything through it.

digraph motor_vars_t { rankdir=LR; node [shape=box, style="filled,rounded", fontname="Helvetica", fontsize=10, margin="0.15,0.08"]; edge [color="#555555"]; MV [label="MOTOR_Vars_t\nmotorVars_M1", fillcolor="#f9ebea", color="#e74c3c", penwidth=2]; IC [label="inputCtrl\n(MOTOR_InputCtrl_t)", fillcolor="#e8daef", color="#8e44ad"]; OV [label="outVars\n(MOTOR_OutVars_t)", fillcolor="#d5f5e3", color="#27ae60"]; SV [label="statusVars\n(MOTOR_StatusVars_t)", fillcolor="#d5f5e3", color="#27ae60"]; MS [label="motorSetsHandle\n→ MOTOR_SetVars_t", fillcolor="#fdebd0", color="#e67e22"]; UP [label="userParamsHandle\n→ USER_Params", fillcolor="#d4e6f1", color="#2980b9"]; HI [label="halInterface\n→ HAL_FOC_Interface_t", fillcolor="#fdebd0", color="#e67e22"]; PI [label="pi_Id, pi_Iq, pi_spd\n(PI_Obj)", fillcolor="#d5f5e3", color="#27ae60"]; ES [label="estHandle\n→ EST_Obj (FAST)", fillcolor="#d4e6f1", color="#2980b9"]; EM [label="esmoHandle\n→ ESMO_Obj", fillcolor="#d4e6f1", color="#2980b9"]; TT [label="tiTuneHandle\n→ TiTune_Obj", fillcolor="#d4e6f1", color="#2980b9"]; TR [label="traj_spd\n(TRAJ_Obj)", fillcolor="#f2f3f4", color="#7f8c8d"]; AG [label="angleGen\n(ANGLE_GEN_Obj)", fillcolor="#f2f3f4", color="#7f8c8d"]; AD [label="adcData\n→ HAL_ADCData_t", fillcolor="#fdebd0", color="#e67e22"]; MV -> IC; MV -> OV; MV -> SV; MV -> MS; MV -> UP; MV -> HI; MV -> PI; MV -> ES; MV -> EM; MV -> TT; MV -> TR; MV -> AG; MV -> AD; }


SYSTEM_Vars_t — System-Level Flags

File: motor_common.h (global: systemVars in main.c)

SYSTEM_Vars_t holds system-wide flags shared between the ISR and the background loop. It is separate from MOTOR_Vars_t to allow multi-motor configurations.

Field

Description

flagInitializeDone

Set after all init functions complete

flagEnableSystem

Background loop runs while this is true

flagOffsetCalibDone

Set by ISR when ADC offset calibration completes

timerCntFOCCtrlISR

ISR tick counter — used to gate the 1 ms background loop

powerRelayWaitTime_ms

Relay energize delay before motor start

dacCtrl1, dacCtrl2

DAC debug output control (serial plot)


Structure Initialization Flow

digraph init_flow { rankdir=TB; node [shape=box, style="filled,rounded", fontname="Helvetica", fontsize=10, margin="0.25,0.1"]; edge [color="#555555"]; A [label="main()", fillcolor="#d4e6f1", color="#2980b9"]; B [label="initMotor1Handles()\nLinks all handles inside MOTOR_Vars_t\n(motorSetsHandle, userParamsHandle,\nhalInterface, esmoHandle, tiTuneHandle, ...)", fillcolor="#fdebd0", color="#e67e22"]; C [label="initMotor1CtrlParameters()\nCopies Motor_ParamsType → USER_Params\nCopies Motor_ParamsType → MOTOR_SetVars_t\nComputes timing counts from time macros", fillcolor="#fdebd0", color="#e67e22"]; D [label="initMotorControlSystem()\nRegisters ISR, enables PWM,\ninitializes gate driver,\ncalls setupControllers()", fillcolor="#fdebd0", color="#e67e22"]; E [label="setupControllers()\nComputes PI gains from USER_Params:\nKp_Id = Ls_d × BWc\nKi_Id = 0.25 × Rs/Ls_d × T\nKp_spd = J × BWs / (1.5 × P × λ)", fillcolor="#d5f5e3", color="#27ae60"]; F [label="ISR running\nAll structures live, FOC executing", fillcolor="#f9ebea", color="#e74c3c"]; A -> B -> C -> D -> E -> F; }


HAL FOC Data Object

HAL_FOC_Data_Obj — Hardware Interface Runtime Data

File: hal_foc_interface.h

HAL_FOC_Data_Obj is the mutable runtime data object that sits at the boundary between the FOC algorithm and the physical hardware. It is allocated in RAM and passed by pointer through the HAL_FOC_Interface_t to every vtable function. The ISR reads ADC results from it, writes PWM duty-cycle values into it, and checks gate-driver fault status through it — all in a single ISR tick.

digraph hal_foc_data { rankdir=LR; node [shape=box, style="filled,rounded", fontname="Helvetica", fontsize=10, margin="0.15,0.08"]; edge [color="#555555", fontname="Helvetica", fontsize=8]; ISR [label="FOC ISR", fillcolor="#f9ebea", color="#e74c3c", penwidth=2]; ADC [label="adcData\n(HAL_ADCData_t)\nI_A, VdcBus_V\noffset_I_ad / offset_Idc_ad\ncurrent_sf, voltage_sf", fillcolor="#d4e6f1", color="#2980b9"]; PWM [label="pwmData\n(HAL_PWMData_t)\nVabc_pu, cmpValue[]\nperiod, deadband\nflagEnablePwm", fillcolor="#d5f5e3", color="#27ae60"]; GD [label="gdDataHandle\n(const HAL_GD_DATA_Obj *)\ngdMaxCurrentA, gdCurrentSF\ngdOverVolVal, gdUnderVolVal\ngdVolSF (read-only)", fillcolor="#fdebd0", color="#e67e22"]; CMP [label="compOffsetData[3]\nDAC trip-point counts\n[0]=PhA/DC-link\n[1]=PhB [2]=PhC", fillcolor="#e8daef", color="#8e44ad"]; OC [label="pOverCurLimA\n(float32_t *)\nOver-current threshold\nin Amps", fillcolor="#f2f3f4", color="#7f8c8d"]; ISR -> ADC [label="reads"]; ISR -> PWM [label="writes"]; ISR -> GD [label="reads (fault)"]; ISR -> CMP [label="reads/writes\n(cal)"]; ISR -> OC [label="reads"]; }

Field Reference

Field

Type

Direction

Description

motorNum

MotorNum_e

Config

Motor instance identifier (M1, M2, …)

numCurrentSensors

uint16_t

Config

Number of phase-current ADC channels (1 or 3)

numVoltageSensors

uint16_t

Config

Number of DC-bus voltage ADC channels

boardKit

Board_Kit_e

Config

Board variant identifier

currentSenseType

CURRENTSEN_Type_e

Config

Sensing topology: three-shunt or single-shunt

pwmData

HAL_PWMData_t

Written by ISR

PWM duty-cycle data — see PWM Data

flagEnableOffsetCalc

bool

Control

Set true to trigger ADC offset calibration

pOverCurLimA

float32_t *

Config

Pointer to over-current trip threshold in Amps

ipdCurrentLimit

float32_t

Config

IPD injection current limit in Amps

adcData

HAL_ADCData_t

Written by ISR

ADC phase-current and bus-voltage results — see ADC Data

compOffsetData[3]

uint16_t[3]

Cal output

Comparator DAC trip-point offsets in raw counts (0–4095)

gdDataHandle

const HAL_GD_DATA_Obj *

Read-only

Gate driver scaling constants and fault thresholds — see GD Data

ecapIPDPulseTime

uint32_t

Read

ECAP capture value for the last IPD pulse width


ADC Data — HAL_ADCData_t

File: hal_data.h

HAL_ADCData_t is embedded directly inside HAL_FOC_Data_Obj as the adcData field. Every ISR tick the topology-specific ReadPhaseCurrents and ReadInverterVoltages vtable functions convert raw ADC counts into physical units and store the results here. The FOC algorithm then reads adcData.I_A and adcData.VdcBus_V directly.

Field

Unit

Description

VdcBus_V

V

DC bus voltage — used for per-unit voltage normalisation

I_A

A

Three-phase currents (Ia, Ib, Ic) after offset removal and scaling

V_V

V

Three-phase voltages (Va, Vb, Vc)

Idc1_A

A

DC-link current up-count samples (single-shunt only)

Idc2_A

A

DC-link current down-count samples (single-shunt only)

offset_Idc_ad

ADC counts

DC-link current offset — accumulated during offset calibration (single-shunt)

offset_I_ad

ADC counts

Per-phase current offsets (Xa, Xb, Xc) — accumulated during offset calibration (three-shunt)

offset_V_sf

V/count

Phase voltage offset scale factors

current_sf

A/count

Current scale factor — converts raw ADC count to Amps

voltage_sf

V/count

Phase voltage scale factor

dcBusvoltage_sf

V/count

DC bus voltage scale factor

ADC Offset Calibration

Before the motor starts, the ISR runs an offset calibration loop controlled by flagEnableOffsetCalc. During this phase:

  1. HAL_RunOffsetCalInit() zeroes the accumulator registers.

  2. HAL_RunOffsetCalStep() is called once per ISR tick for offsetCalibTimeSet_cnt ticks (set in MOTOR_SetVars_t).

  3. Each call accumulates the raw ADC reading into offset_I_ad (three-shunt) or offset_Idc_ad (single-shunt).

  4. When the count expires the average is stored and flagOffsetCalibDone is set in SYSTEM_Vars_t.

After calibration, every ReadPhaseCurrents call subtracts the stored offset before applying current_sf, so I_A always represents true zero-mean phase current.

/* Typical ISR offset calibration sequence */
if (systemVars.flagOffsetCalibDone == FALSE)
{
    halFOCDataObj.flagEnableOffsetCalc = TRUE;
    HAL_RunOffsetCalInit(&motorVars_M1.halInterface);

    /* Called each ISR tick until complete */
    uint8_t done = HAL_RunOffsetCalStep(&motorVars_M1.halInterface,
                                        motorVars_M1.statusVars.offsetCalibTimeCnt,
                                        motorSetVars_M1.offsetCalibTimeSet_cnt);
    if (done)
    {
        systemVars.flagOffsetCalibDone = TRUE;
        halFOCDataObj.flagEnableOffsetCalc = FALSE;
    }
}

PWM Data — HAL_PWMData_t

File: hal_data.h

HAL_PWMData_t is embedded inside HAL_FOC_Data_Obj as the pwmData field. At the end of every ISR tick the FOC algorithm writes the computed voltage vector into pwmData.Vabc_pu and then calls HAL_SetPhaseVoltages(), which converts the per-unit values to hardware compare registers.

Field

Unit

Description

Vabc_pu

pu

Three-phase duty-cycle commands in per-unit (−1.0 … +1.0) — written by the SVPWM/iPark stage

cmpValue[3]

PWM counts

Computed compare values loaded into MCPWM compare registers

cmpAValue[3]

PWM counts

Compare-A shadow values (used for asymmetric PWM)

cmpBValue[3]

PWM counts

Compare-B shadow values

upSoc[2]

PWM counts

ADC SOC trigger point on the up-count (for current sampling)

downSoc[2]

PWM counts

ADC SOC trigger point on the down-count (single-shunt second sample)

deadband

PWM counts

Deadband insertion in PWM clock cycles

noiseWindow

PWM counts

Blanking window around switching edge to avoid sampling noise

minCMPValue

PWM counts

Minimum compare value — enforces minimum on-time

adcSample

PWM counts

ADC sample timing offset from PWM peak

period

PWM counts

PWM period register value

socCMP

PWM counts

SOC compare value for the ADC trigger

flagEnablePwm

bool

true = PWM outputs active; false = outputs forced low

pVab_out_V

V

Pointer to the alpha-beta voltage vector produced by the current PI controllers

Data flow into pwmData

digraph pwm_flow { rankdir=LR; node [shape=box, style="filled,rounded", fontname="Helvetica", fontsize=9, margin="0.15,0.08"]; edge [color="#555555", fontname="Helvetica", fontsize=8]; PI [label="Current PI\nVdq_out_V", fillcolor="#d5f5e3", color="#27ae60"]; IP [label="iPark\nVab_out_V", fillcolor="#d5f5e3", color="#27ae60"]; SV [label="SVPWM\nVabc_pu", fillcolor="#d4e6f1", color="#2980b9"]; PD [label="pwmData.Vabc_pu\n→ cmpValue[]", fillcolor="#fdebd0", color="#e67e22"]; HW [label="MCPWM\nCompare Regs", fillcolor="#f9ebea", color="#e74c3c"]; PI -> IP -> SV -> PD -> HW [label="HAL_SetPhaseVoltages()"]; }


Gate Driver Data — HAL_GD_DATA_Obj

File: hal_gate_driver.h

gdDataHandle inside HAL_FOC_Data_Obj is a read-only pointer to the HAL_GD_DATA_Obj that is owned by the gate driver interface (HAL_GD_Interface_t). It is set once during initMotorControlSystem() and never changes at runtime.

The FOC layer uses gdDataHandle to read board-level scaling constants and protection thresholds without needing to know which physical gate driver IC is fitted. This keeps the FOC algorithm independent of the gate driver variant (DRV8323RH, DRV8329A, etc.).

Field

Unit

Description

gdMaxCurrentA

A

Maximum allowable phase current — used to range-check the over-current threshold

gdCurrentSF

A/count

Current scale factor derived from the gate driver’s sense resistor and amplifier gain

gdCurrSensDelay

s

Current sensing propagation delay — used to compensate ADC sample timing

gdCurrSampDelay

s

Current sampling delay — additional blanking after the gate driver output

gdCurrOffset

A

Current offset correction specific to the gate driver hardware

gdCurrSign

—

Sign correction (+1.0 or −1.0) for current polarity depending on shunt placement

gdOverVolVal

V

Over-voltage fault threshold — compared against adcData.VdcBus_V

gdUnderVolVal

V

Under-voltage fault threshold — compared against adcData.VdcBus_V

gdVolSF

V/count

Voltage scale factor for the gate driver’s voltage sense circuit

gdPhVoltOffsetSF

V/count

Phase voltage offset scale factor

gdVolFilterPoleFreqRPS

rad/s

Pole frequency of the DC bus voltage low-pass filter

How gdDataHandle communicates fault status

The gdDataHandle pointer provides the FOC layer with the thresholds needed to detect gate-driver-level faults. The fault detection flow is:

  1. Hardware trip — The gate driver IC asserts its nFAULT pin when an over-current or over-temperature event occurs. This is wired to a PWM trip-zone input, which immediately forces all PWM outputs low in hardware without software intervention.

  2. Software detection — Each ISR tick the motor state machine reads adcData.VdcBus_V and compares it against gdDataHandle->gdOverVolVal and gdDataHandle->gdUnderVolVal to detect DC bus faults. Phase current magnitude is compared against *pOverCurLimA (which is initialised from gdDataHandle->gdMaxCurrentA scaled by the user’s over-current factor).

  3. Fault latch — When a fault is detected, the state machine sets the corresponding bit in motorVars_M1.outVars.faultMtrNow and transitions to MOTOR_FAULT_STOP state.

  4. Fault clear — HAL_clearMtrFaultStatus() calls the vtable function which clears the gate driver’s nFAULT latch (via SPI or GPIO) and resets the PWM trip-zone latch, allowing the motor to restart after the user sets inputCtrl.flagClearFaults = true.

/* Typical fault check pattern in the ISR state machine */
if (motorVars_M1.halInterface.halFOCDataHandle->adcData.VdcBus_V >
    motorVars_M1.halInterface.halFOCDataHandle->gdDataHandle->gdOverVolVal)
{
    motorVars_M1.outVars.faultMtrNow.bit.overVoltage = 1U;
}

if (motorVars_M1.halInterface.halFOCDataHandle->adcData.VdcBus_V <
    motorVars_M1.halInterface.halFOCDataHandle->gdDataHandle->gdUnderVolVal)
{
    motorVars_M1.outVars.faultMtrNow.bit.underVoltage = 1U;
}

Note

gdDataHandle is declared const HAL_GD_DATA_Obj * — the FOC layer can only read the gate driver data. All writes to HAL_GD_DATA_Obj are performed exclusively by the gate driver initialisation code in initMotorControlSystem(). This enforces a clean ownership boundary: the gate driver layer owns its data; the FOC layer consumes it.


Comparator DAC Offset Data — compOffsetData[3]

compOffsetData stores the raw DAC count (0–4095) at which each hardware comparator trips during the comparator offset calibration sweep. These values are used to compensate for comparator input offset voltage so that the hardware over-current trip threshold accurately reflects the programmed current limit in Amps.

Index

Channel

Description

[0]

Phase-A / DC-link

Trip-point DAC count for phase-A shunt (three-shunt) or DC-link shunt (single-shunt)

[1]

Phase-B

Trip-point DAC count for phase-B shunt (three-shunt only)

[2]

Phase-C

Trip-point DAC count for phase-C shunt (three-shunt only)

The calibration is performed once at startup by calling HAL_CompOffsetCalInit() followed by repeated calls to HAL_CompOffsetCalStep() until it returns 1. The found offsets are then added to the nominal DAC threshold when HAL_SetCompOCLimits() programs the comparator DAC registers.