Electronic – Run code once in lifetime of an embedded C program

cembeddedmicrocontroller

How can I make a code snippet run only once in the lifetime of a program? It can be turned off and turned on many times. The only option to run the code snippet again must be flashing the board again.

The code is a Calibration Section which I don't want to run again. If I use EEPROM or Flash we will be setting a Flag to true or False. So When we first read that memory location what would be the random value in that memory area?

What is the best method to implement this in embedded C?

Best Answer

Your microcontroller might have some EEPROM, OTP memory, user fuse bits, where you can set a flag.

There is no "best method in embedded C", writing nonvolatile memory is different in every microcontroller.

edit:

FLASH

Flash memory contents are erased while programming the device. After programming, all bytes that weren't written contain 0xFF. Consult the datasheet to find an area that can be safely programmed from within the running firmware.

EEPROM

Although it's not guaranteed in the datasheets, all EEPROMs I've seen so far contained 0xFF:s when shipped from the factory (except ones preprogrammed with an unique MAC address, but that's explicitly documented). Some programming devices/software are able to erase or program EEPROM contents too. Some can be write protected, permanently or reversibly.

OTP

One Time Programmable memory always contains well defined initial values, documented in the datasheet.

It's always a good idea to include a good checksum like CRC32 with the data written, to protect against data corruption caused by defective parts, transmission errors, cosmic rays, whatever.