cancel
Showing results for 
Search instead for 
Did you mean: 

Simple example program to read and write option bytes on STM32F042K6 using HAL libraries?

dale
Associate III
Posted on May 16, 2017 at 06:41

Can someone show me a simple program to read and write the option bytes on the STM32042K6 using the STM32 HAL libraries?  I only want to store an 8-bit value.  I'm not interested in reading or modifying the read or write protection, etc.

I've been able to write the option bytes using the ST-LINK utility software, and then successfully been able to read one of them back using the following C code (Atollic TrueSTUDIO 7.1.2):

mode = HAL_FLASHEx_OBGetUserData(OB_DATA_ADDRESS_DATA0); // from option byte 0

...and this works just fine.  Now I want to be able to update the option byte in code as the application is running.  All I need to store is 8 bits.  I don't think I need to allocate 1K of FLASH memory as EEPROM emulation at this point.  I'm porting a trivial program from an 8-bit AVR that had dedicated EEPROM on-chip.

I've looked and looked at the HAL documentation concerning the HAL_FLASHEx_OBProgram() function, and I understand that the FLASH and the option bytes need to be unlocked before erasing and writing the data, but I have no idea how to populate the FLASH_OBProgramInitTypeDef structure needed in the ...Program() function.  No examples are given in the HAL documentation (UM1785).

Any suggestions or examples would be greatly appreciated.

Thank you,

Dale

1 REPLY 1
dale
Associate III
Posted on May 17, 2017 at 02:06

I've had the benefit of a good night's sleep and was able to come up with some code that seems to work on the STM32042K6 for reading and writing option byte 0.

Reading the bytes is simple enough:

mode = HAL_FLASHEx_OBGetUserData(OB_DATA_ADDRESS_DATA0); // from option byte 0

Writing takes a bit more code, as the FLASH and option bytes have to be unlocked first:

FLASH_OBProgramInitTypeDef OBInit; // programming option structure

OBInit.DATAAddress = OB_DATA_ADDRESS_DATA0; // address of type FLASHEx_OB_Data_Address

OBInit.DATAData = mode; // mode value to be saved

OBInit.OptionType = OPTIONBYTE_DATA; // of type FLASHEx_OB_Type

// unlock FLASH in general

if(HAL_FLASH_Unlock() == HAL_OK) {

   // unlock option bytes in particular

   if(HAL_FLASH_OB_Unlock() == HAL_OK) {

      // erase option bytes before programming

      if(HAL_FLASHEx_OBErase() == HAL_OK) {

         // program selected option byte

         HAL_FLASHEx_OBProgram(&OBInit); // result not checked as there is no recourse at this point

         if(HAL_FLASH_OB_Lock() == HAL_OK) {

            HAL_FLASH_Lock(); // again, no recourse

            //HAL_FLASH_OB_Launch(); // reset occurs here (sorry, debugger)

         }

      }

   }

}

I hope this helps someone (perhaps even me) in the future.