In the first post of this series, we covered the basic ideas behind creating an STM32 bootloader. Today we will focus on the application code and generate output, that our bootloader code will be able to process.

The application code is very simple – it inits one pin at output and toggles it after some time. Here is the code listing:

#include "stm32f411xe.h"

int main(void) {

  int i = 0;


  GPIOD->MODER = GPIO_MODER_MODER14_0; // Set PD14 as output (LD5), red LED

  while (1) {
    GPIOD->ODR ^= (GPIO_ODR_ODR_14);   // Toggle the LED
    for (i = 0; i < 1000000; i++)
    // do nothing, just loose some time

We will generate a .SREC file (Motorola S-record) after successful compilation of the source code above. To do so we will use the following command:

fromelf --m32 --output=Output\Output.srec Output\Output.axf

fromelf is an image converter tool and the rest are the parameters we pass to it

–m32 command tells fromelf to produce 32 bit S-record output

–output=Output\Output.srec parameter tells fromelf where to place the generated .SREC file

Output\Output.axf specifies the input object file

We place it in Project\Options for Target ‘Application’\User tab, under After Build/Rebuild Run #1

After successful project build, the Output.srec file is generated in Output folder. Let’s rename it to Output_red.srec, indicating that the red LED is blinking.

To test out bootloader, we want to be sure that is successfully writes the new code, by sending another one. We will do this by generating another output file, this time blinking the blue LED. Change line 9 to:

GPIOD->MODER = GPIO_MODER_MODER15_0; // Set PD15 as output (LD6), blue LED

and line 12 to:

GPIOD->ODR ^= (GPIO_ODR_ODR_15);   // Toggle the LED

Build the project again and rename Output.srec to Output_blue.srec

In the next part we will send the .SREC files (first the red, then test it and then the blue and test again) to the microcontroller via UART and write it to the flash.