Hall Sensor Calibration

Hall sensors provide discrete rotor position feedback at six fixed electrical angles (60° apart). However, due to manufacturing tolerances and magnetic asymmetries, the actual transition angles deviate from the ideal 60° spacing. Additionally, Hall sensors fire at different edges depending on rotation direction — leading edge during forward rotation, trailing edge during reverse.

This creates a systematic 60° error if a single angle table is used for both directions. Hall Sensor Auto Calibration automatically measures and corrects these errors by sweeping the rotor through a full mechanical cycle in both forward and reverse directions, recording the actual transition angles for each Hall state, and producing separate calibration tables for bidirectional operation.

Why Two Calibration Tables Are Required

A Hall sensor fires when the rotor’s magnetic pole crosses the sensor threshold:

  • Forward rotation: Sensor fires at the leading edge of the pole (entering the sensor zone).

  • Reverse rotation: Same sensor fires at the trailing edge of the pole (leaving the sensor zone).

The difference between leading and trailing edges is approximately one full 60° sector. Using a single table for both directions introduces a systematic 60° error in one direction, causing:

  • Severe torque loss or reversal

  • Unstable current control

  • Potential motor stall or runaway

Solution: Maintain separate calAngleFwd_rad[8] and calAngleRev_rad[8] tables, selected at runtime based on the direction of rotation.

Calibration Sequence Overview

The Hall calibration state machine executes the following steps:

Step

State

Purpose

1

HALL_CAL_ALIGN

Lock rotor at 0° with d-axis current to establish reference

2

HALL_CAL_FWD_DITHER_* / HALL_CAL_FWD_SAMPLE

Sweep angle 0° → 360°×polePairs×mechCycles, accumulate transition angles

3

HALL_CAL_REV_ALIGN

Re-lock rotor at 0° before reversing

4

HALL_CAL_REV_DITHER_* / HALL_CAL_REV_SAMPLE

Sweep angle backward, accumulate reverse transition angles

5

HALL_CAL_AVERAGE

Divide accumulated sums by (numMechCycles × numPolePairs) to compute mean angles

6

HALL_CAL_DONE

Validate tables and signal completion

Key Design Features

  • Direct Accumulation: No raw sample buffer. Angles are accumulated directly into per-state sums during the sweep. Total RAM footprint: ~160 bytes.

  • State-Triggered Optimization: On each Hall state transition, the sweep angle jumps 45° ahead (or backward in reverse), reducing calibration time by ~85% while maintaining a safe 15° margin before the next 60° transition.

  • Deterministic Completion: The number of transitions per state is known at init time (numMechCycles × numPolePairs), enabling integer-based completion detection.

  • Dither Settling: Before sampling, the rotor is dithered ±90° around the sweep angle to allow mechanical settling and ensure stable Hall state detection.

Configuration

Hall calibration parameters are defined in the motor configuration files and passed to the calibration engine at runtime.

Configuration Structure

typedef struct _HallCal_Config_t_
{
    float32_t alignCurrent_A;     /* D-axis align current (A) */
    float32_t calCurrent_A;       /* D-axis current during sweep (A) */
    float32_t stepSize_rad;       /* Angle increment per step (rad), e.g. π/180 = 1° */
    float32_t ditherFwdAngle_rad; /* Forward dither offset (rad), e.g. 91° */
    float32_t ditherRevAngle_rad; /* Reverse dither offset (rad), e.g. 90° */
    float32_t alignHoldTime_ms;   /* Align hold duration (ms), e.g. 50.0 */
    float32_t ditherHoldTime_ms;  /* Dither half-cycle hold (ms), e.g. 5.0 */
    uint16_t  numMechCycles;      /* Full mechanical cycles per sweep direction */
} HallCal_Config_t;

Configuration Location

Hall calibration parameters are typically defined in:

  • Motor-specific macros: motor_params.h — per-motor calibration settings

  • Motor parameter struct: motor_params.c — Motor_ParamsType initializer

  • Application initialization: mtr1_init.c — consumed by the motor control initialization

Example Configuration

/* In motor_params.h — define per-motor Hall calibration macros */
#define MOTOR_<NAME>_HALL_CAL_ALIGN_CURRENT_A    (1.0f)
#define MOTOR_<NAME>_HALL_CAL_CURRENT_A          (0.5f)
#define MOTOR_<NAME>_HALL_CAL_STEP_SIZE_DEG      (1.0f)
#define MOTOR_<NAME>_HALL_CAL_DITHER_FWD_DEG     (91.0f)
#define MOTOR_<NAME>_HALL_CAL_DITHER_REV_DEG     (90.0f)
#define MOTOR_<NAME>_HALL_CAL_ALIGN_HOLD_MS      (50.0f)
#define MOTOR_<NAME>_HALL_CAL_DITHER_HOLD_MS     (5.0f)
#define MOTOR_<NAME>_HALL_CAL_MECH_CYCLES        (2U)

/* In motor_params.c — populate the Motor_ParamsType struct */
.HallCalAlignCurrent_A    = MOTOR_<NAME>_HALL_CAL_ALIGN_CURRENT_A,
.HallCalCurrent_A         = MOTOR_<NAME>_HALL_CAL_CURRENT_A,
.HallCalStepSize_rad      = (MOTOR_<NAME>_HALL_CAL_STEP_SIZE_DEG * MATH_PI) / 180.0f,
.HallCalDitherFwdAngle_rad = (MOTOR_<NAME>_HALL_CAL_DITHER_FWD_DEG * MATH_PI) / 180.0f,
.HallCalDitherRevAngle_rad = (MOTOR_<NAME>_HALL_CAL_DITHER_REV_DEG * MATH_PI) / 180.0f,
.HallCalAlignHoldTime_ms  = MOTOR_<NAME>_HALL_CAL_ALIGN_HOLD_MS,
.HallCalDitherHoldTime_ms = MOTOR_<NAME>_HALL_CAL_DITHER_HOLD_MS,
.HallCalMechCycles        = MOTOR_<NAME>_HALL_CAL_MECH_CYCLES,

Key Parameters

Parameter

Type

Description

Typical Value

Notes

alignCurrent_A

float32_t

D-axis current during alignment phase

1.0 A

Must be sufficient to hold rotor against load

calCurrent_A

float32_t

D-axis current during sweep phase

0.5 A

Lower than align current to reduce heating

stepSize_rad

float32_t

Angle increment per ISR tick (no state transition)

π/180 (1°)

Smaller steps = higher resolution, longer calibration

ditherFwdAngle_rad

float32_t

Forward dither offset from sweep angle

91° (π/2 + π/180)

Asymmetric to bracket the transition

ditherRevAngle_rad

float32_t

Reverse dither offset from sweep angle

90° (π/2)

Symmetric backward offset

alignHoldTime_ms

float32_t

Duration to hold alignment current

50.0 ms

Allow rotor to settle; increase for high-inertia loads

ditherHoldTime_ms

float32_t

Duration to hold each dither position

5.0 ms

Allow mechanical settling before sampling Hall state

numMechCycles

uint16_t

Number of full mechanical cycles per sweep direction

2

More cycles = higher accuracy, longer calibration

Parameter Tuning Guidelines

alignCurrent_A and calCurrent_A:

  • Must be high enough to overcome friction and load torque

  • Too high → excessive heating, potential demagnetization

  • Typical range: 0.5–2.0 A depending on motor size

stepSize_rad:

  • Default 1° (π/180 rad) is a good compromise

  • Smaller steps (0.5°) improve resolution but extend calibration time

  • Larger steps (2°) reduce time but may miss transitions

ditherFwdAngle_rad and ditherRevAngle_rad:

  • Asymmetric dither (91° forward, 90° reverse) brackets the transition zone

  • Ensures rotor settles on both sides of the transition before sampling

  • Typical range: 85°–95°

alignHoldTime_ms and ditherHoldTime_ms:

  • Must be long enough for mechanical settling

  • Too short → Hall state may not stabilize, causing missed transitions

  • Typical: 50 ms for align, 5 ms for dither

numMechCycles:

  • 1 cycle: Fast but lower accuracy (6 transitions per state)

  • 2 cycles: Good balance (12 transitions per state, averaged)

  • 3+ cycles: Higher accuracy but longer calibration time

Note

Calibration Time Estimate:

With state-triggered optimization (45° jumps on transitions):

  • 6 states × numMechCycles transitions per state

  • ~85% time reduction vs. continuous 1° stepping

  • Typical total time: 30–60 seconds for 2 mechanical cycles

Without optimization (continuous stepping):

  • Would require ~360° × numPolePairs × numMechCycles / stepSize_rad steps

  • Example: 360° × 4 poles × 2 cycles / 1° = 2880 steps

  • At 5 ms dither hold per step: ~14 seconds per direction

Watch Window — Runtime Monitoring and Control

In CCS or IAR, add the following expressions to the watch window to monitor calibration progress and control the state machine at runtime without rebuilding:

Calibration State and Progress

Watch Window Expression

Type

Description

motorVars_M1.inputCtrl.flagStartHallCal

bool

Set true to trigger Hall calibration sequence

hallCalData.state

HallCal_State_e

Current calibration state (0=IDLE, 1=ALIGN, …, 10=DONE)

hallCalData.statesFound

uint8_t

Number of Hall states detected so far (0–6 per direction)

hallCalData.statesRequired

uint8_t

Number of states still required (countdown from 6 to 0)

hallCalData.sweepAngle_rad

float32_t

Current sweep angle in radians

hallCalData.flagCalDone

bool

TRUE when averaging is complete

hallCalData.flagCalValid

bool

TRUE if calibration tables pass sanity checks

Calibrated Angle Tables

Watch Window Expression

Type

Description

hallCalData.calAngleFwd_rad[1] through [6]

float32_t

Forward calibration table (indexed by Hall state 1–6)

hallCalData.calAngleRev_rad[1] through [6]

float32_t

Reverse calibration table (indexed by Hall state 1–6)

Accumulated Sums (Diagnostic)

Watch Window Expression

Type

Description

hallCalData.calAngleFwdSum_rad[1] through [6]

float32_t

Running sum of angles for forward direction (before averaging)

hallCalData.calAngleRevSum_rad[1] through [6]

float32_t

Running sum of angles for reverse direction (before averaging)

Example Watch Window Session

  1. Start calibration: Set motorVars_M1.inputCtrl.flagStartHallCal = true

  2. Monitor progress: Watch hallCalData.statesFound increment from 0 to 6 (forward), then 0 to 6 (reverse)

  3. Check completion: Wait for hallCalData.flagCalDone == true and hallCalData.flagCalValid == true

  4. Inspect results: View hallCalData.calAngleFwd_rad[1..6] and hallCalData.calAngleRev_rad[1..6]

  5. Verify spacing: Adjacent angles should differ by ~60° (pi/3 rad ≈ 1.047 rad)

  6. Update permanent tables: Copy the calibrated values into HAL_Hall_AngleTable_rad_fwd and HAL_Hall_AngleTable_rad_rev in hal_hall_sen_interface.h — see note below.

Note

Calibration is a one-time setup step. The runtime calibration engine stores results in RAM (hallCalData.calAngleFwd_rad / hallCalData.calAngleRev_rad). These values are lost on power cycle.

For production use, once you have verified the calibrated angles produce correct motor operation, manually copy the calibrated values into the static lookup tables HAL_Hall_AngleTable_rad_fwd and HAL_Hall_AngleTable_rad_rev in hal_hall_sen_interface.h (see code block below), then rebuild and flash. The motor will use the permanent calibrated tables on every power cycle without needing to re-run calibration.

static const float32_t HAL_Hall_AngleTable_rad_fwd[8] = {
    0.0f,                  /* 0b000 = INVALID */
    <calAngleFwd_rad[1]>,  /* state 1 */
    <calAngleFwd_rad[2]>,  /* state 2 */
    <calAngleFwd_rad[3]>,  /* state 3 */
    <calAngleFwd_rad[4]>,  /* state 4 */
    <calAngleFwd_rad[5]>,  /* state 5 */
    <calAngleFwd_rad[6]>,  /* state 6 */
    0.0f                   /* 0b111 = INVALID */
};
static const float32_t HAL_Hall_AngleTable_rad_rev[8] = {
    0.0f,                  /* 0b000 = INVALID */
    <calAngleRev_rad[1]>,  /* state 1 */
    <calAngleRev_rad[2]>,  /* state 2 */
    <calAngleRev_rad[3]>,  /* state 3 */
    <calAngleRev_rad[4]>,  /* state 4 */
    <calAngleRev_rad[5]>,  /* state 5 */
    <calAngleRev_rad[6]>,  /* state 6 */
    0.0f                   /* 0b111 = INVALID */
};

Calibration Algorithm Details

State Machine Flow

IDLE
  ↓
ALIGN (hold d-axis current for alignHoldTime_ms)
  ↓
FWD_DITHER_FWD (apply +ditherFwdAngle_rad for ditherHoldTime_ms)
  ↓
FWD_DITHER_REV (apply -ditherRevAngle_rad for ditherHoldTime_ms)
  ↓
FWD_SAMPLE (sweep angle, detect Hall transitions, accumulate)
  ├─ On transition: jump +45°, return to FWD_DITHER_FWD
  ├─ No transition: increment by stepSize_rad, return to FWD_DITHER_FWD
  └─ All 6 states found: proceed to REV_ALIGN
  ↓
REV_ALIGN (re-lock at 0° for alignHoldTime_ms)
  ↓
REV_DITHER_FWD (apply +ditherFwdAngle_rad for ditherHoldTime_ms)
  ↓
REV_DITHER_REV (apply -ditherRevAngle_rad for ditherHoldTime_ms)
  ↓
REV_SAMPLE (sweep angle backward, detect Hall transitions, accumulate)
  ├─ On transition: jump -45°, return to REV_DITHER_FWD
  ├─ No transition: decrement by stepSize_rad, return to REV_DITHER_FWD
  └─ All 6 states found: proceed to AVERAGE
  ↓
AVERAGE (background: divide sums by numMechCycles × numPolePairs)
  ↓
VALIDATE (check sector spacing: 60° ± 20°)
  ↓
DONE (tables ready for use)

Angle Accumulation (Direct Accumulation Design)

During FWD_SAMPLE and REV_SAMPLE, whenever a Hall state transition is detected:

/* Forward sweep */
calAngleFwdSum_rad[hallState] += sweepAngle_rad;

/* Reverse sweep */
calAngleRevSum_rad[hallState] += sweepAngle_rad;

After all transitions are detected, the background loop calls HallCal_average():

/* Compute mean angle for each state */
for (stateIdx = 1; stateIdx <= 6; stateIdx++)
{
    calAngleFwd_rad[stateIdx] = (calAngleFwdSum_rad[stateIdx] * 6) / statesRequired;
    calAngleRev_rad[stateIdx] = (calAngleRevSum_rad[stateIdx] * 6) / statesRequired;
}

The divisor statesRequired = numMechCycles × numPolePairs is computed at init time.

Validation

After averaging, HallCal_validate() checks that adjacent transition angles (in forward sequence order 1→3→2→6→4→5→1) are within the expected 60° ± 20° range:

/* For each adjacent pair in forward sequence */
angleDiff_rad = angleTable_rad[stateB] - angleTable_rad[stateA];

/* Wrap to (-pi, pi] to handle 330 deg -> 30 deg wrap-around */
if (angleDiff_rad > MATH_PI)
    angleDiff_rad -= MATH_TWO_PI;
else if (angleDiff_rad < -MATH_PI)
    angleDiff_rad += MATH_TWO_PI;

/* Check if within tolerance: |angleDiff_rad| must be in [40 deg, 80 deg] */
if (fabsf(angleDiff_rad) < SECTOR_MIN_RAD || fabsf(angleDiff_rad) > SECTOR_MAX_RAD)
    flagCalValid = false;

If both forward and reverse tables pass, flagCalValid = true.

Integration with Motor Control

Initialization

In mtr1_init.c, the Hall calibration is initialized with motor parameters:

/* Initialize Hall calibration configuration */
HallCal_Config_t hallCalConfig = {
    .alignCurrent_A     = motorParams->HallCalAlignCurrent_A,
    .calCurrent_A       = motorParams->HallCalCurrent_A,
    .stepSize_rad       = motorParams->HallCalStepSize_rad,
    .ditherFwdAngle_rad = motorParams->HallCalDitherFwdAngle_rad,
    .ditherRevAngle_rad = motorParams->HallCalDitherRevAngle_rad,
    .alignHoldTime_ms   = motorParams->HallCalAlignHoldTime_ms,
    .ditherHoldTime_ms  = motorParams->HallCalDitherHoldTime_ms,
    .numMechCycles      = motorParams->HallCalMechCycles,
};

/* Initialize calibration data */
HallCal_init(&hallCalConfig, &hallCalData, isrPeriod_usec);

ISR Integration

In the FOC ISR, when motorState == MOTOR_HALL_CAL, call the calibration state machine instead of the normal FOC path:

/* In FOC ISR */
if (motorState == MOTOR_HALL_CAL)
{
    /* Run Hall calibration state machine */
    HallCal_run_inline(&hallCalConfig, &hallCalData, hallState,
                       &obj->outVars.angleFOC_rad,
                       &obj->outVars.Idq_out_A.value[0],  /* d-axis */
                       &obj->outVars.Idq_out_A.value[1]); /* q-axis */
}
else
{
    /* Normal FOC control path */
    FOC_run(...);
}

Background Loop Integration

In the main application loop, when hallCalData.state == HALL_CAL_AVERAGE:

/* In background loop */
if (hallCalData.state == HALL_CAL_AVERAGE)
{
    /* Compute averaged tables */
    HallCal_average(&hallCalData, &hallCalConfig);

    /* Validate tables */
    HallCal_validate(&hallCalData);

    if (hallCalData.flagCalValid)
    {
        /* Copy calibrated tables to FOC controller */
        memcpy(hallAngleTable_Fwd, hallCalData.calAngleFwd_rad,
               sizeof(hallAngleTable_Fwd));
        memcpy(hallAngleTable_Rev, hallCalData.calAngleRev_rad,
               sizeof(hallAngleTable_Rev));

        /* Signal completion */
        motorState = MOTOR_READY;
    }
    else
    {
        /* Calibration failed — log error and retry */
        motorState = MOTOR_FAULT;
    }
}

Troubleshooting

Calibration Does Not Complete

Symptom: hallCalData.statesFound does not reach 6 for one or both directions.

Causes:

  • Hall sensor not connected or faulty

  • Hall state not changing during sweep

  • Rotor mechanically stuck or excessive friction

Solutions:

  • Verify Hall sensor wiring and signal levels

  • Check rotor can rotate freely

  • Increase alignCurrent_A and calCurrent_A to overcome friction

  • Increase alignHoldTime_ms and ditherHoldTime_ms for settling

Calibration Completes but flagCalValid == false

Symptom: hallCalData.flagCalDone == true but hallCalData.flagCalValid == false.

Causes:

  • Adjacent transition angles deviate more than ±20° from 60°

  • Hall sensor mounting misaligned

  • Magnetic field asymmetry in motor

Solutions:

  • Physically inspect Hall sensor alignment

  • Check for magnetic asymmetries (e.g., uneven magnet magnetization)

  • Increase numMechCycles to average out transient errors

  • Increase ditherHoldTime_ms to allow better settling

Calibration Tables Show Large Variations

Symptom: calAngleFwd_rad[1..6] or calAngleRev_rad[1..6] have large scatter.

Causes:

  • Insufficient dither settling time

  • Rotor oscillating during sampling

  • Electrical noise on Hall signals

Solutions:

  • Increase ditherHoldTime_ms (e.g., 5 ms → 10 ms)

  • Add RC filtering to Hall signal inputs

  • Increase numMechCycles to average out noise

Forward and Reverse Tables Are Identical

Symptom: calAngleFwd_rad[s] ≈ calAngleRev_rad[s] for all states.

Causes:

  • Hall sensor not actually reversing (mechanical issue)

  • Reverse sweep not executing (state machine stuck)

Solutions:

  • Verify motor can rotate in both directions

  • Check hallCalData.state transitions to HALL_CAL_REV_ALIGN

  • Increase alignHoldTime_ms before reverse sweep

Implementation Files

File

Purpose

hall_cal.h

Hall calibration API and inline ISR function

hall_cal.c

Background functions: HallCal_init(), HallCal_average(), HallCal_validate()

motor_params.h

Motor-specific calibration macros

motor_params.c

Motor parameter struct initializer

mtr1_init.c

Motor initialization and calibration setup

application.c

State machine integration and background loop