simplefoc / Arduino-FOC

Arduino FOC for BLDC and Stepper motors - Arduino Based Field Oriented Control Algorithm Library
https://docs.simplefoc.com
MIT License
2.03k stars 521 forks source link

HallSensor.cpp volatile access bug #244

Closed runger1101001 closed 1 year ago

runger1101001 commented 1 year ago

From: https://community.simplefoc.com/t/lepton-deku-mod/2641/43?u=runger Thanks to Dekutree

I’ve found a tricky bug.

float HallSensor::getVelocity(){ if (pulse_diff == 0 || ((long)(_micros() - pulse_timestamp) > pulse_diff) ) { // last velocity isn't accurate if too old return 0; } else { return direction * (_2PI / (float)cpr) / (pulse_diff / 1000000.0f); } }

Sometimes it returns infinity due to divide by zero, because pulse_diff is volatile and can be changed by interrupt. It needs to be cached in a local variable before checking if it’s equal to zero.

runger1101001 commented 1 year ago

Fixed on dev branch, thanks @dekutree !

Will be part of 2.3 release