cancel
Showing results for 
Search instead for 
Did you mean: 

What is a good methodology for object oriented peripheral code in C?

Roth.Ian
Associate II

I have a project that involves a STM32F7 controlling a stepper motor through GPIO. I have now been tasked with redesigning it with a ST L6470, a motor control IC which has a SPI interface. I would like have a shared codebase so that a simple #define could be used at compile time to choose between GPIO or SPI code depending on the board used. Examples of polymorphism in C such as the linux device driver code and GObject are difficult to understand and perhaps not a good example for microcontroller code.

The solution must be C11 compatible and compiled in IAR EWARM.

13 REPLIES 13

Actually you could put all the functions and parameters for a motor type in a Class. Then reference instances of the required class with a pointer from the main control algorithm. The compiler won't include anything for unused classes so saves all the ifdefs and so on.

Well, yeah, if there's multiple drivers in the future, then #defines are not the way to go (ignore my prev post 🙂). Your original post sounded like that was not likely, so I was shooting for short term simplicity.

Damage control 😂

This is also the reason why interleaving cubeMX generated code with user code using #define anchors makes versioning trickier

S.Ma
Principal

If your source code is intuitive, easy to understand and reuse by someone else, easy to extract sub functionality and plumb it to another project, then it would be good.

For example, which variable needs an app note?

int32 Temp;

or

int32 STTS751_TempDegC_x100;

?