There’s been a bunch of discussion on discord about how to integrate it, it’s tricky for a couple of reasons.
First, it’s very performance sensitive. In order for that balancer to work it’s doing the equivalent of calling loopFOC, in foc_current mode, at >80kHz. Any pattern that either involves recalculating things, or significantly more branching should be considered undesirable. Right now it’s only really useful on the fastest STM32’s, the slowest that might have a shot at running it reliably with enough overhead to be useful is probably the f401 at 84MHz. I’d like to find some more time by optimizing the setPwm function, it takes significantly longer than necessary at ~3us last I looked. Beyond that to allow it to run on more chips we’d need to consider fixed point/integer math instead of floats.
The other reason integration into either the sensor or current sense classes is tricky is that to accomplish the injection and demodulation you need access to the electrical angle, unfiltered current sense values, motor parameters, the driver frequency, and setting the driver pwm. You also end up needing to give everything a pointer to everything else and it started to look like a mess. The default filters (velocity and angle) in the motor/sensor class would also break HFI tracking if you relied on the motor class and put HFI in a sensor class, the solution there is for HFI to track angle, but then you have the same value duplicated in multiple objects, but with different filters, so they’re not actually the same. Putting it in its own motor class made it a lot easier to manage. Also, conceptually I like to organize classes that emulate hardware so that the hardware boundaries and class boundaries vaguely line up, and the physics that make HFI work actually happen in the motor.
All that said, I’m really pretty new to writing c++ and would be more than happy to see how someone else would manage integrating this how you describe.
On code duplication, there’s a lot of stuff I left in the HFIBLDCMotor class for compatibility, but it never actually gets called. For example loopFOC just takes a fast path return if HFI is on. I think a good way to reduce that is to refactor things like the sensor alignment, open loop, etc to be compatible with both BLDC and stepper motors and move those into FOCMotor, possibly with a weak ref.
If we accept a motor class for it (I proposed putting it in the drivers repo) then the rest of the changes to the library are near zero. The driver class needs a getPwmState function, and the current sense class needs to provide a user call back function that’s executed in the ADC ISR. Additionally we’d need to change the implementation of inlinecurrentsense to synchronize with the driver, unless we’re ok with my compiler define hack in the low side current sense. Otherwise that’s pretty much it.