Skip to content

Commit 7b7b4ad

Browse files
committed
fix CCW hallsensor bug + glitch interrupt avoidance
1 parent ba1ded0 commit 7b7b4ad

File tree

2 files changed

+16
-6
lines changed

2 files changed

+16
-6
lines changed

src/sensors/HallSensor.cpp

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -43,21 +43,31 @@ void HallSensor::handleC() {
4343
*/
4444
void HallSensor::updateState() {
4545
long new_pulse_timestamp = _micros();
46-
hall_state = C_active + (B_active << 1) + (A_active << 2);
46+
47+
int8_t new_hall_state = C_active + (B_active << 1) + (A_active << 2);
48+
49+
// glitch avoidance #1 - sometimes we get an interrupt but pins haven't changed
50+
if (new_hall_state == hall_state) {
51+
return;
52+
}
53+
hall_state = new_hall_state;
54+
4755
int8_t new_electric_sector = ELECTRIC_SECTORS[hall_state];
4856
static Direction old_direction;
4957
if (new_electric_sector - electric_sector > 3) {
5058
//underflow
51-
direction = static_cast<Direction>(natural_direction * -1);
59+
direction = Direction::CCW;
5260
electric_rotations += direction;
5361
} else if (new_electric_sector - electric_sector < (-3)) {
5462
//overflow
55-
direction = static_cast<Direction>(natural_direction);
63+
direction = Direction::CW;
5664
electric_rotations += direction;
5765
} else {
58-
direction = (new_electric_sector > electric_sector)? static_cast<Direction>(natural_direction) : static_cast<Direction>(natural_direction * (-1));
66+
direction = (new_electric_sector > electric_sector)? Direction::CW : Direction::CCW;
5967
}
6068
electric_sector = new_electric_sector;
69+
70+
// glitch avoidance #2 changes in direction can cause velocity spikes. Possible improvements needed in this area
6171
if (direction == old_direction) {
6272
// not oscilating or just changed direction
6373
pulse_diff = new_pulse_timestamp - pulse_timestamp;
@@ -97,7 +107,7 @@ float HallSensor::getVelocity(){
97107
if (pulse_diff == 0 || ((_micros() - pulse_timestamp) > pulse_diff) ) { // last velocity isn't accurate if too old
98108
return 0;
99109
} else {
100-
return direction * (_2PI / cpr) / (pulse_diff / 1000000.0);
110+
return natural_direction * direction * (_2PI / cpr) / (pulse_diff / 1000000.0);
101111
}
102112

103113
}

src/sensors/HallSensor.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ class HallSensor: public Sensor{
8080
*/
8181
int needsAbsoluteZeroSearch() override;
8282

83-
// whether last step was CW (+1) or CCW (-1) direction
83+
// whether last step was CW (+1) or CCW (-1). Note - this is a raw direction (i.e. doesn't include natural_direction reversal)
8484
Direction direction;
8585

8686
void attachSectorCallback(void (*onSectorChange)(int a) = nullptr);

0 commit comments

Comments
 (0)