Skip to content

Commit 248f9fe

Browse files
Fix hall sensor velocity estimation
The hall sensor velocity estimation could end up returning a nonzero value if the timer "wrapped" between runs, even if the motor was actually stationary. If using the velocity regulator the motor may then fail to start. To solve this: - Switch to using unsigned types so that wrapping is defined. - When timing out the pulse value, also reset it so that the velocity won't be briefly treated as valid again when the timer wraps. Seen on a platform with 32 bit long, so running the motor and then waiting ~40 minutes is enough to observe this bug. Note that the pulse_diff variable is reset if the hall sensor direction changes, which may happen naturally when the motor stops, depending on what it is attached to.
1 parent f9e9a2d commit 248f9fe

File tree

2 files changed

+13
-4
lines changed

2 files changed

+13
-4
lines changed

src/sensors/HallSensor.cpp

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -122,10 +122,19 @@ float HallSensor::getSensorAngle() {
122122
*/
123123
float HallSensor::getVelocity(){
124124
noInterrupts();
125-
long last_pulse_timestamp = pulse_timestamp;
126-
long last_pulse_diff = pulse_diff;
125+
unsigned long last_pulse_timestamp = pulse_timestamp;
126+
unsigned long last_pulse_diff = pulse_diff;
127127
interrupts();
128-
if (last_pulse_diff == 0 || ((long)(_micros() - last_pulse_timestamp) > last_pulse_diff*2) ) { // last velocity isn't accurate if too old
128+
if (last_pulse_diff == 0) {
129+
return 0;
130+
} else if ((_micros() - last_pulse_timestamp) > last_pulse_diff*2) {
131+
// Last velocity isn't accurate if too old.
132+
// Reset to avoid the diff being used again when the time wraps.
133+
noInterrupts();
134+
if (pulse_diff == last_pulse_diff) {
135+
pulse_diff = 0;
136+
}
137+
interrupts();
129138
return 0;
130139
} else {
131140
return direction * (_2PI / (float)cpr) / (last_pulse_diff / 1000000.0f);

src/sensors/HallSensor.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ class HallSensor: public Sensor{
9090
// function pointer for on sector change call back
9191
void (*onSectorChange)(int sector) = nullptr;
9292

93-
volatile long pulse_diff;
93+
volatile unsigned long pulse_diff;
9494

9595
};
9696

0 commit comments

Comments
 (0)