Best way to compile .hex file with different serial number in the sketch

Hi everyone,
i have a program that i want to upload in several cards. The program is same for all the card except a variable which is the serial number. Each card must have its own serial number (hard coded in the program or maybe in the flash).

I would like to automatise the process to :

  • change this variable (serial number) automatically
  • compile the program
  • upload the program.

For compile and upload, no problem, but is there a good solution to modify the program for a variable ?

Thank you.

R-One

If you're willing to re-compile the sketch for each hard-coded serial number, I think the easiest way is with a preprocessor directive.

Just reference something like SERIALNUMBER inside your code. For instance:

const int serialNumber = SERIALNUMBER;

That will declare an integer variable with your serial number you can use however you like. It's value will be set at compile time as follows.

You then pass "-DSERIALNUMBER=xxxxxxxxxx" to the compiler. This will replace the above reference to SERIALNUMBER with whatever you provide at compile time. But note you could get type errors during the compilation if you pass something other than an int.

It appears you can pass command line arguments to the compiler with "arduino-cli compile --build-properties". I haven't used it but from other posts on here it works something like this:

arduino-cli compile -b a:b:c --build-properties build.extra_flags=-DSERIALNUMBER=xxxxxxxxxx .

You can loop the compile in your build script and change SERIALNUMBER to a unique number every time. References inside your binary will then include that number/string.

Thanks homediggity,
that's a perfect response for my use case !
I didn't think about this solution. Thank you.