Making code cross platform


I’m working with both Gen2 and multiple Gen3 devices. I would like to make my code to work across both platforms, but was wondering what the best way to do this would be. Any suggestions for “best practices”?

One thing I was thinking of was to make use of PLATFORM_IDs. Perhaps do something like the below. I have yet to try this and this is on my “TODO” list, but I would just like to start a conversation + get some ideas while I clear my backlog or at least be told “Yeah your going in the right direction” and I’ll figure it out.

Relevant Docs

What I am thinking of…

     // Boron code goes here (e.g. Cellular.setActiveSIM(), Cellular.setCredentials(), RGB.onChange() etc...)
     // Maybe some WIFI settings here...
     // Electron code goes here(e.g. cellular_credentials_set(), RGB.mirrorTO() etc...)

Found something useful:

I guess its #if (PLATFORM_ID == PLATFORM_XXX) rather than the #ifdef in the OP, but the idea is the same.

There are also other “flags” the rather focus on available features instead of platform

#if Wiring_WiFi 
// WiFi specific stuff
#elif Wiring_Cellular
// Cellular specific stuff
// or

I also use this to abstract away WiFi or Cellular specifics

#if Wiring_WiFi 
  #define RADIO WiFi
#elif Wiring_Cellular
  #define RADIO Cellular
  // somewhere in code

Here you can find some of the defined platforms and features


@ScruffR thanks for the suggestion.

This is a good one. So instead of being platform specific I could check for feature or hardware flags. I could then use a combination of these flags to perhaps make a wrapper to abstract the specifics (and call something generic my main function (i.e. just like your RADIO example).

I’ll do this in my next refactor, I’ll probably start with the most common place which is the void setup(), this always has device/feature specific calls!

1 Like

Yes, checking for the feature is always better than checking for the platform.

For example, the Boron SoM has a different PLATFORM_ID than the Boron, but if you check for Wiring_Cellular instead of the PLATFORM_ID your code would probably work without modification.