By executing the following command, the binary file is converted into an image file and generated in the “build” folder. In this command, “xxx” denotes the software version, “bootloader” the current folder name, and “application” the target application name.
& "C:\ST\STM32CubeIDE_x.x.x\STM32CubeIDE\plugins\com.st.stm32cube.ide.mcu.externaltools.gnu-tools-for-stm32.x.x.x\tools\bin\arm-none-eabi-objcopy.exe" -I binary -O elf32-littlearm -B arm --rename-section .data=.bootloader_image,alloc,load,readonly,data,contents bootloader\Debug\bootloader.bin application\Core\Lib\bootloader_image.o
Enter the following code into the linker script and overwrite the area where memory is written, then save the changes.
.bootloader_image :
{
. = ALIGN(4);
KEEP(*(.bootloader_image))
. = ALIGN(4);
} >FLASH
The following is an example of code that writes the binary data from the image file into the flash region. By the way, the CPU in use is the STM32F4.
const uint8_t *src = _binary_Bootloader_Debug_Bootloader_bin_start;
uint32_t size = (uint32_t)(_binary_Bootloader_Debug_Bootloader_bin_end
- _binary_Bootloader_Debug_Bootloader_bin_start);
/* Unlock flash */
HAL_FLASH_Unlock();
/* Erase sectors 0-3 (bootloader area: 0x08000000 - 0x0800FFFF, 64KB) */
FLASH_EraseInitTypeDef erase = {
.TypeErase = FLASH_TYPEERASE_SECTORS,
.Sector = FLASH_SECTOR_0,
.NbSectors = 4,
.VoltageRange = FLASH_VOLTAGE_RANGE_3
};
uint32_t sectorError = 0;
HAL_FLASHEx_Erase(&erase, §orError);
/* Program flash word-by-word (4 bytes at a time) */
uint32_t wordCount = size / 4;
uint32_t remainder = size % 4;
const uint32_t *src32 = (const uint32_t *)src;
for (uint32_t i = 0; i < wordCount; i++) {
HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, BOOTLOADER_ADDRESS + i * 4, src32[i]);
}
/* Program remaining bytes (if size is not 4-byte aligned) */
if (remainder > 0) {
uint32_t lastWord = 0xFFFFFFFF;
memcpy(&lastWord, src + wordCount * 4, remainder);
HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, BOOTLOADER_ADDRESS + wordCount * 4, lastWord);
}
HAL_FLASH_Lock();
First, right-click on the project and select “Properties” Next, open “C/C++ Build” -> “Settings” and under “MCU GCC Linker,” select “Miscellaneous” Then, click the “Add” button next to “Additional object files” enter the following, click “Apply and Close” and finally compile to complete the process.
${workspace_loc:/application/Core/Lib/bootloader_image.o}
