@@ -43,21 +43,31 @@ void HallSensor::handleC() {
4343 */
4444void 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}
0 commit comments