@@ -43,21 +43,31 @@ void HallSensor::handleC() {
43
43
*/
44
44
void HallSensor::updateState () {
45
45
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
+
47
55
int8_t new_electric_sector = ELECTRIC_SECTORS[hall_state];
48
56
static Direction old_direction;
49
57
if (new_electric_sector - electric_sector > 3 ) {
50
58
// underflow
51
- direction = static_cast < Direction>(natural_direction * - 1 ) ;
59
+ direction = Direction::CCW ;
52
60
electric_rotations += direction;
53
61
} else if (new_electric_sector - electric_sector < (-3 )) {
54
62
// overflow
55
- direction = static_cast < Direction>(natural_direction) ;
63
+ direction = Direction::CW ;
56
64
electric_rotations += direction;
57
65
} 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 ;
59
67
}
60
68
electric_sector = new_electric_sector;
69
+
70
+ // glitch avoidance #2 changes in direction can cause velocity spikes. Possible improvements needed in this area
61
71
if (direction == old_direction) {
62
72
// not oscilating or just changed direction
63
73
pulse_diff = new_pulse_timestamp - pulse_timestamp;
@@ -97,7 +107,7 @@ float HallSensor::getVelocity(){
97
107
if (pulse_diff == 0 || ((_micros () - pulse_timestamp) > pulse_diff) ) { // last velocity isn't accurate if too old
98
108
return 0 ;
99
109
} else {
100
- return direction * (_2PI / cpr) / (pulse_diff / 1000000.0 );
110
+ return natural_direction * direction * (_2PI / cpr) / (pulse_diff / 1000000.0 );
101
111
}
102
112
103
113
}
0 commit comments