From e2990da04611b63593dbca82382d5057d291554d Mon Sep 17 00:00:00 2001 From: stijncarelsbergh Date: Thu, 8 Oct 2026 00:04:25 +0200 Subject: [PATCH] fix(hall sensor): initialise the state and don't fake a rotation at start-up The constructor left hall_state, electric_sector, electric_rotations, total_interrupts, pulse_diff, pulse_timestamp, direction, old_direction and use_interrupt uninitialised - indeterminate values for any sensor that is not in the BSS section, and wrong FOC start-up behaviour even for globals. init() then called updateState(), which compares the measured sector against that uninitialised/zeroed sector and, when the rotor happens to sit in sector 4 or 5 at power-up, interprets the difference as an electrical underflow and starts with electric_rotations = -1 (2 of the 6 power-up positions). The angle and the accumulated full rotations are offset by one electrical rotation until something resets them. Instead of relying on updateState() the first time, the current hall state is adopted directly. --- src/sensors/HallSensor.cpp | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/src/sensors/HallSensor.cpp b/src/sensors/HallSensor.cpp index 64c5e48c1..2f4c95dcb 100644 --- a/src/sensors/HallSensor.cpp +++ b/src/sensors/HallSensor.cpp @@ -18,6 +18,19 @@ HallSensor::HallSensor(int _hallA, int _hallB, int _hallC, int _pp){ // extern pullup as default pullup = Pullup::USE_EXTERN; + + // initialise the state variables - they would otherwise be indeterminate + // for sensors that do not live in the BSS section (heap/stack instances) + use_interrupt = false; + hall_state = 0; + electric_sector = 0; + electric_rotations = 0; + total_interrupts = 0; + pulse_diff = 0; + pulse_timestamp = _micros(); + A_active = B_active = C_active = 0; + direction = Direction::UNKNOWN; + old_direction = Direction::UNKNOWN; } // HallSensor interrupt callback functions @@ -156,11 +169,15 @@ void HallSensor::init(){ pinMode(pinC, INPUT); } - // init hall_state + // adopt the current hall state as the starting point instead of calling + // updateState(): that would compare the measured sector with the zeroed + // one and count a spurious +-1 electric rotation for 2 of the 6 power-up + // positions, offsetting the angle and the full-rotation counter A_active = digitalRead(pinA); B_active = digitalRead(pinB); C_active = digitalRead(pinC); - updateState(); + hall_state = C_active + (B_active << 1) + (A_active << 2); + electric_sector = ELECTRIC_SECTORS[hall_state]; pulse_timestamp = _micros();