stm32f103cbt6 bootloader

stm32f103c8t6 的bootloader也可以按照这个来做,因为两者只有flash部分不同而已。

这里我用我做过的一个项目为例,使用stm32f103cbt6为例:

        STM32F103CBT6是一款32位ARM Cortex-M3内核的微控制器,由意法半导体公司(STMicroelectronics)生产。 该微控制器具有128KB的闪存(flash)和20KB的SRAM,以及多种外设,例如ADC(模数转换器)、DAC(数字模拟转换器)、定时器、PWM(脉宽调制器)、USART(通用同步/异步串行收发器)等。 它还支持多种通信接口,如SPI、I2C、CAN等。 STM32F103CBT6芯片具有低功耗、高性能、高可靠性和丰富的外设接口,适用于各种应用场合,如工业自动化、智能家居、消费电子等。

一:STM32Cubmx配置

①芯片选择:

       ②: 配ST-Link调试接口(防止无法二次烧录程序)

        ③配时钟外设

        ④串口配置(用于printf输出)

        ⑤时钟树配置

        ⑥工程配置

二:分配 flash

       stm32f103cbt6 flash空间为128KB,我这里给分配5KB的flash,bootloader使用0~4页flash空间,大小0x13FF(5KB),若是不够自己根据项目分配即可。

bootloader程序的中断偏移量不需要进行修改

        剩下空间中页5~65(61KB)为主程序app1使用空间,页66~126(61KB)为OTA升级时拷贝程序空间,其中第126页的最后2字节位置存储OTA升级标识符。最后一页存储系统配置

注意!!!主程序烧录起始地址为0x8001400,大小为0xF400

选择-Q3,优化代码

烧录时擦除的区域

!!!若要修改主程序起始地址,一定要记得修改中断向量表偏移量!!!

三、Keil基础设置

四、远程OTA升级流程

        OTA升级:主要是在主程序app1中执行,收到升级指令后,关闭所有任务,下载固件数据拷贝到APP2位置,然后将升级标识位置1,再次启动时bootloader程序检测到标识为1则会进行升级,将app2程序拷贝到app1区域

五、代码

/* USER CODE BEGIN Header */
/**
 ******************************************************************************
 * @file           : main.c
 * @brief          : Main program body
 ******************************************************************************
 * @attention
 *
 * Copyright (c) 2025 STMicroelectronics.
 * All rights reserved.
 *
 * This software is licensed under terms that can be found in the LICENSE file
 * in the root directory of this software component.
 * If no LICENSE file comes with this software, it is provided AS-IS.
 *
 ******************************************************************************
 */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "stdio.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
#define Application_Size 0xF400U // app1 、app2应用程序,各自占用flash:61KB

#define Application_1_Addr 0x08001400U //  应用程序1的首地址(主应用程序地址)  占用flash:61KB
#define Application_2_Addr 0x08010800U //  应用程序2的首地址(OTA 下载地址)    占用flash:61KB

#define OTA_FLAG_ADDR (Application_2_Addr + Application_Size - 2) // app2区域最后的两个字节用于存储 OTA 升级标志位 (0x0801FBFE)

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
// 重定向
int fputc(int ch, FILE *f)
{
  HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 10);
  return (ch);
}

// 跳转函数 - 跳转到 APP1
void Ctrl_Program_Jump(unsigned int app_address)
{
  typedef void (*pFunction)(void);
  unsigned int JumpAddress = 0;
  static pFunction Jump_To_Application;

  if (((*(__IO unsigned int *)app_address) & 0x2FFE0000) == 0x20000000) // 校验栈顶地址是否有效
  {
    SysTick->CTRL = 0;                                     // 关闭系统定时器,防止进入中断
    __disable_irq();                                       // 关闭全局中断,避免跳转中断发散
    JumpAddress = *(__IO unsigned int *)(app_address + 4); // 取出复位向量地址
    Jump_To_Application = (pFunction)JumpAddress;
    __set_MSP(*(__IO unsigned int *)app_address); // 设置主堆栈指针(MSP)
    Jump_To_Application();                        // 跳转执行主程序
  }
}

// 正向擦除指定区域(从前往后擦除)
void wz_flash_erase_init(uint32_t addr, uint32_t size)
{
  HAL_FLASH_Unlock(); // 解锁 FLASH
  FLASH_EraseInitTypeDef EraseInit;
  uint32_t PageError = 0;

  // 擦除指定区域
  EraseInit.TypeErase = FLASH_TYPEERASE_PAGES;
  EraseInit.Banks = FLASH_BANK_1;
  EraseInit.PageAddress = addr;               // 擦除地址
  EraseInit.NbPages = size / FLASH_PAGE_SIZE; // 擦除页数
  HAL_FLASHEx_Erase(&EraseInit, &PageError);  // 擦除指定区域

  HAL_FLASH_Lock(); // 上锁
}

// 反向擦除指定区域(从后往前擦除)
void wz_flash_erase_reverse(uint32_t start_addr, uint32_t size)
{
  HAL_FLASH_Unlock();

  FLASH_EraseInitTypeDef EraseInit;
  uint32_t PageError = 0;

  uint32_t page_size = FLASH_PAGE_SIZE;
  uint32_t page_count = size / page_size;

  for (int i = page_count - 1; i >= 0; i--)
  {
    EraseInit.TypeErase = FLASH_TYPEERASE_PAGES;
    EraseInit.Banks = FLASH_BANK_1;
    EraseInit.PageAddress = start_addr + i * page_size;
    EraseInit.NbPages = 1;

    if (HAL_FLASHEx_Erase(&EraseInit, &PageError) != HAL_OK)
    {
      // 可以打印或记录 PageError
      break;
    }
  }

  HAL_FLASH_Lock();
}

// 向指定地址写入数据
static void wz_WriteFlash(uint32_t addr, uint32_t *buff, uint32_t word_size)
{
  HAL_FLASH_Unlock();
  for (int i = 0; i < word_size; i++)
  {
    HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, addr + 4 * i, buff[i]);
  }
  HAL_FLASH_Lock();
}

// 从指定地址读取数据
static void wz_ReadFlash(uint32_t addr, uint32_t *buff, uint32_t word_size)
{
  for (int i = 0; i < word_size; i++)
  {
    buff[i] = *(__IO uint32_t *)(addr + 4 * i); // 读取数据
  }
}

// 将app2的代码写入app1
void Copy_App2_To_App1(void)
{
  printf(">Start-copy......
");
  int loopcnt = Application_Size / 1024;
  // printf("loopcnt = %d
", loopcnt);
  uint32_t temp[256];
  for (int i = 0; i < loopcnt; i++)
  {
    wz_ReadFlash((Application_2_Addr + i * 1024), temp, 256); // 每次读取 1KB 数据(256 x 4 字节)
    wz_WriteFlash((Application_1_Addr + i * 1024), temp, 256);
  }
  printf("> Copy down......
");
}
/* USER CODE END 0 */

/**
 * @brief  The application entry point.
 * @retval int
 */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_USART1_UART_Init();
  /* USER CODE BEGIN 2 */
  printf("**********BootLoader**********
");

  // 读取OTA升级标志位
  uint8_t ota_data = *(volatile uint8_t *)OTA_FLAG_ADDR;
  // printf("ota_data = %d
", ota_data);

  // 判断是否进行 OTA 升级
  if (ota_data == 1)
  {
    // 擦除 APP1 区域
    wz_flash_erase_init(Application_1_Addr, Application_Size);
    // APP2代码写入APP1
    Copy_App2_To_App1();
    // 擦除 APP2 区域
    // wz_flash_erase_init(Application_2_Addr, Application_Size);
    wz_flash_erase_reverse(Application_2_Addr, Application_Size);
  }

  // 进入app1主程序
  Ctrl_Program_Jump(Application_1_Addr);
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
 * @brief System Clock Configuration
 * @retval None
 */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
   * in the RCC_OscInitTypeDef structure.
   */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
   */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
 * @brief  This function is executed in case of error occurrence.
 * @retval None
 */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef USE_FULL_ASSERT
/**
 * @brief  Reports the name of the source file and the source line number
 *         where the assert_param error has occurred.
 * @param  file: pointer to the source file name
 * @param  line: assert_param error line source number
 * @retval None
 */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d
", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

© 版权声明
THE END
如果内容对您有所帮助,就支持一下吧!
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容