PID parameters in a cross-platform example sketch

Hi all,

For my project I’m trying to write a generic SimpleFOC program that performs closed loop velocity control with FOC current control.

By generic I mean that I want it to support all of the MCUs we are testing (Arduino R4, ESP32s3, STM32), all of the drivers (SimpleFOCShield, DRV8302, Driveshield), and all of the motors (GM4108H, EzRun 1626SD and others). The idea is that the correct header files containing the settings for the user’s choice of MCU, driver, encoder and motor will be loaded at compile time.

The header files define the constants that will be needed elsewhere in the sketch, e.g

BLDCMotor motor = BLDCMotor(MOTOR_POLE_PAIRS);
BLDCDriver3PWM driver = BLDCDriver3PWM(BOARD_PWM_A_PIN, BOARD_PWM_B_PIN, BOARD_PWM_C_PIN, BOARD_EN_PIN);
Encoder encoder = Encoder(BOARD_ENC_A_PIN, BOARD_ENC_B_PIN, ENCODER_PPR);

etc.

My question is, what about the PID parameters? Would I put them in the header file that contains MCU settings? Or are they part of the motor or driver settings? Or are the optimum PID settings affected by all of the above?

I am aware that the optimal P setting can be affected by the clock speed of the MCU. But does it also depend on motor and driver features?

If so I worry that my whole approach of trying to support multiple hardware setups is doomed to fail.

Hey,

So the PID parameters are very system specific, and they do depend on the hardware being used. Different drivers will probably lead to different PID tuning values, although I would have said this is less important than the MCU speed (loop speed), the motor, and the load characteristics.

So yeah, it is system-specific I’m afraid.

But if you have a bunch of different versions of the PID parameters (for example due to MCU type), then putting them in a header file for the given hardware combo is a good way to solve it. This way the code can be the same across your different setups, and its just the hardware header which is different per setup.
All the hardware-specific stuff like pin assignments, current sense gains, motor parameters and PID tunings can go into that header.
If you write it in the right way, e.g.

#if !defined(MOTOR_POLE_PAIRS)
#define MOTOR_POLE_PAIRS    7
#endif

Then you can even override your defines from the environment’s build flags, for example from the board definition files or platformio.ini …

Thanks Runger, it seems like I’ll have to define a separate header file for every hardware combination. Still, doing it this way will totally work even if it is a bit verbose.

Another complication is that some drivers (e.g DRV8302) require special init code to set the values of specific pins, the header files for those drivers potentially need to contain some actual code (not just #defines).

Working on it.