simplefoc / Arduino-FOC-drivers

Drivers and support code for SimpleFOC
https://docs.simplefoc.com/drivers_library
MIT License
156 stars 67 forks source link

CalibratedSensor computes incorrect electrical angle for CCW sensor direction #24

Closed SwapnilPande closed 11 months ago

SwapnilPande commented 1 year ago

Hi all,

I've been chasing down a bug in which a motor + encoder + driver has poor performance when the sensor is in the CCW direction, but has good performance when the sensor is in the CW direction.

I've found that the CalibratedSensor computes the zero_electrical_angle incorrectly if the sensor direction is detected to be CCW during the calibration routine. The correct electrical angle appears to be 2*PI - electrical_angle, which I verified by checking the electrical angle computed by the default calibration routine (not using the CalibratedSensor).

I've traced this incorrect calculation down to this line: https://github.com/simplefoc/Arduino-FOC-drivers/blob/72c1a9ee636bf876a373acc5410dfa35da03fc6d/src/encoders/calibrated/CalibratedSensor.cpp#L156

where the encoder mechanical angle is not negated if the sensor direction is CCW. I fixed this by changing the line to the following:

avg_elec_angle += _normalizeAngle(directionSensor*_wrapped.getMechanicalAngle()*_NPP);

After making this change, the default calibration routine AND the routine from the CalibratedSensor return the same zero electrical angle and the motor runs well with both sensor directions.

I would be happy to submit a PR if this appears to be the correct way to handle this bug!

runger1101001 commented 1 year ago

Sounds like you’ve found a bug! I’m not at my computer at the moment, but I’ll look into this and integrate your change as soon as I can

runger1101001 commented 1 year ago

PR has been merged to the dev branch...

runger1101001 commented 11 months ago

This is now released, so I will close the issue. Thanks for the PR!