#include "stm32f0xx_hal.h"
/* Notes:
Need to have DFU jump right to the program to unset those option bytes, or somehow have dfu-util unset them. Probably try using the :leave parameter...
Flashing a binary file to address 0x8004000 of device memory and ask the device to leave DFU mode:
$ dfu-util -a 0 -s 0x08004000:leave -D /path/to/image.bin
*/
// Unset bootloader option bytes
void bootloader_unset(void)
{
FLASH_OBProgramInitTypeDef OBParam;
HAL_FLASHEx_OBGetConfig(&OBParam);
if(OBParam.USERConfig != 0xFF)
{
OBParam.OptionType = OPTIONBYTE_USER;
OBParam.USERConfig = 0xFF;
HAL_FLASH_Unlock();
HAL_FLASH_OB_Unlock();
HAL_FLASHEx_OBErase();
HAL_FLASHEx_OBProgram(&OBParam);
HAL_FLASH_OB_Lock();
HAL_FLASH_OB_Launch();
}
}
// See thread: https://my.st.com/public/STe2ecommunities/mcu/Lists/cortex_mx_stm32/Flat.aspx?RootFolder=https%3a%2f%2fmy.st.com%2fpublic%2fSTe2ecommunities%2fmcu%2fLists%2fcortex_mx_stm32%2fJump%20to%20USB%20DFU%20Bootloader%20in%20startup%20code%20on%20STM32F042&FolderCTID=0x01200200770978C69A1141439FE559EB459D7580009C4E14902C3CDE46A77F0FFD06506F5B¤tviews=185
// Set option bytes to enter bootloader upon reset
void bootloader_enter(void) {
FLASH_OBProgramInitTypeDef OBParam;
HAL_FLASHEx_OBGetConfig(&OBParam);
// FIXME TODO: CHECK THESE OPTION BYTES, he was using an F1 processor. What about the switch flag?
OBParam.OptionType = OPTIONBYTE_USER;
/*Reset NBOOT0 and BOOT_SEL, see: RM 2.5 Boot configuration*/
OBParam.USERConfig = 0x77; //Sorry for magic number :)
HAL_FLASH_Unlock();
HAL_FLASH_OB_Unlock();
HAL_FLASHEx_OBErase();
HAL_FLASHEx_OBProgram(&OBParam);
HAL_FLASH_OB_Lock();
HAL_FLASH_Lock();
HAL_FLASH_OB_Launch();
}
// Clock configuration
void systemclock_config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct;
RCC_ClkInitTypeDef RCC_ClkInitStruct;
RCC_PeriphCLKInitTypeDef PeriphClkInit;
// Enable HSI48 for main system clock
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI48|RCC_OSCILLATORTYPE_HSI14;
RCC_OscInitStruct.HSI48State = RCC_HSI48_ON;
RCC_OscInitStruct.HSI14State = RCC_HSI14_ON;
RCC_OscInitStruct.HSI14CalibrationValue = 16;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
HAL_RCC_OscConfig(&RCC_OscInitStruct);
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_SYSCLK;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI48;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1);
PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USB;
PeriphClkInit.UsbClockSelection = RCC_USBCLKSOURCE_HSI48;
HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit);
__SYSCFG_CLK_ENABLE();
}