simplefoc / Arduino-FOC

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

[SOLVED][BUG] Issue with more than one HallSensor instance rotating in different directions #324

Closed Everymann closed 7 months ago

Everymann commented 8 months ago

hello there,

I'll briefly explain the problem and how you can fix it.

[Problem] If more than one HallSensor is used, all modes that use getVelocity() from HallSensor go crazy.

You can check it if the test from the examples/utils/sensor_test/hall_sensors folder is used and at least two HallSensors are initialized. If you turn the motors in the opposite direction of rotation (from the sensors point of view), you will very often get a value of zero in the sensor.getVelocity() Print.

[Reason] in a line of the HallSensor.cpp file the variable old_direction is created as static. This passes the same value to all HallSensor instances.

[FIX] You can fix the problem easily by deleting line 56

https://github.com/simplefoc/Arduino-FOC/blob/f9e9a2d29e912957bd75302d4f9a83a1cdff37a5/src/sensors/HallSensor.cpp#L55-L57

  static Direction old_direction;

from the function void HallSensor::updateState() in the src/sensors/HallSensor.cpp file.

After this adding the following line in HallSensor.h to the class HallSensor in file src/sensors/HallSensor.h:

    Direction old_direction;

add it to line 65 for example https://github.com/simplefoc/Arduino-FOC/blob/f9e9a2d29e912957bd75302d4f9a83a1cdff37a5/src/sensors/HallSensor.h#L63-L65

now the variable old_direction is used for its own instance.

runger1101001 commented 8 months ago

You are absolutely right, and your suggested fix will be part of the next release...