什么是单Bank升级:将Flash划分为以下3个区域。
BootLoader区:程序进行升级的引导程序,根据Upade_Flag来判断跳转Bank区运行程序或是接收升级数据写入Bank,接收完成后擦写Upade_Flag区,进行跳转Bank区运行程序。
Upade_Flag区:判断BootLoader是否能跳转IAP程序的标志位。
Bank区:用户程序区。
1.芯片:STM32G071RBT6(意法半导体)
2.开发环境:keil5
对于单片机做IAP功能,首先我们要了解它的Flash大小。我们查看他的数据手册看下Flash大小。
根据上图可知MCU Flash为128k。
根据上图可知Flash分布为2k一页共64页。
由此可将Flash进行划分:
BootLoader:0x08000000 - 0x08002FFF(12K)
Upade_Flag:0x08003000 - 0x080037FF(2K)
Bank:0x08003800 - 0x0801FFFF(114K)
打开STM32CubeMX进行配置
选择STM32G071RBT6
配置时钟为64M
配置串口1
获取工程文件
接下来进行工程设置,BootLoader工程Flash空间为12kb
以下为我修改过的文件。
main.c文件
#include "main.h"
#include "stdio.h"
#include "Update.h"
UART_HandleTypeDef huart1;
UART_HandleTypeDef huart2;
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_USART1_UART_Init(void);
int fputc(int ch, FILE *f)
{
HAL_UART_Transmit(&huart2, (uint8_t *)&ch, 1, 0xFFFF);
return ch;
}
void Uart_Send_Data(uint8_t* Buffer, uint32_t Data_Len)
{
HAL_UART_Transmit(&huart1, Buffer, Data_Len, 0xFFFF);
}
typedef void (*pFunction)(void);
pFunction Jump_To_Application;
uint32_t JumpAddress;
void Jump_To_App(uint32_t address)
{
if (((*(__IO uint32_t*)address) & 0x2FFE0000) == 0x20000000)
{
JumpAddress = *(__IO uint32_t*) (address + 4);
Jump_To_Application = (pFunction) JumpAddress;
__set_MSP(*(__IO uint32_t*) address);
Jump_To_Application();
}
}
static void MX_USART2_UART_Init(void)
{
huart2.Instance = USART2;
huart2.Init.BaudRate = 115200;
huart2.Init.WordLength = UART_WORDLENGTH_8B;
huart2.Init.StopBits = UART_STOPBITS_1;
huart2.Init.Parity = UART_PARITY_NONE;
huart2.Init.Mode = UART_MODE_TX_RX;
huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart2.Init.OverSampling = UART_OVERSAMPLING_16;
huart2.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
huart2.Init.ClockPrescaler = UART_PRESCALER_DIV1;
huart2.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
if (HAL_UART_Init(&huart2) != HAL_OK)
{
Error_Handler();
}
if (HAL_UARTEx_SetTxFifoThreshold(&huart2, UART_TXFIFO_THRESHOLD_1_8) != HAL_OK)
{
Error_Handler();
}
if (HAL_UARTEx_SetRxFifoThreshold(&huart2, UART_RXFIFO_THRESHOLD_1_8) != HAL_OK)
{
Error_Handler();
}
if (HAL_UARTEx_DisableFifoMode(&huart2) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART2_Init 2 */
/* USER CODE END USART2_Init 2 */
}
int main(void)
{
uint8_t R_Buff[1] = {0};
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_USART1_UART_Init();
MX_USART2_UART_Init();
ClearRxQueue();
Read_Flash_Data(R_Buff, 1, FLASH_Updata_Flag_ADDR);
printf("Bootloader R_Buff = 0x%x\r\n", R_Buff[0]);
while (1)
{
if(R_Buff[0] == 0x55)
{
printf("Jump_To_App = %x\r\n", FLASH_APP_ADDR);
Jump_To_App(FLASH_APP_ADDR);
}
else
{
Usart_Data_Handler();
//printf("BootLoader \r\n");
}
}
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/** Configure the main internal regulator output voltage
*/
HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1);
/** Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure.
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSIDiv = RCC_HSI_DIV1;
RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
RCC_OscInitStruct.PLL.PLLM = RCC_PLLM_DIV1;
RCC_OscInitStruct.PLL.PLLN = 8;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2;
RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
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_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
{
Error_Handler();
}
}
/**
* @brief USART1 Initialization Function
* @param None
* @retval None
*/
static void MX_USART1_UART_Init(void)
{
/* USER CODE BEGIN USART1_Init 0 */
/* USER CODE END USART1_Init 0 */
/* USER CODE BEGIN USART1_Init 1 */
/* USER CODE END USART1_Init 1 */
huart1.Instance = USART1;
huart1.Init.BaudRate = 115200;
huart1.Init.WordLength = UART_WORDLENGTH_8B;
huart1.Init.StopBits = UART_STOPBITS_1;
huart1.Init.Parity = UART_PARITY_NONE;
huart1.Init.Mode = UART_MODE_TX_RX;
huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart1.Init.OverSampling = UART_OVERSAMPLING_16;
huart1.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
huart1.Init.ClockPrescaler = UART_PRESCALER_DIV1;
huart1.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
if (HAL_UART_Init(&huart1) != HAL_OK)
{
Error_Handler();
}
if (HAL_UARTEx_SetTxFifoThreshold(&huart1, UART_TXFIFO_THRESHOLD_1_8) != HAL_OK)
{
Error_Handler();
}
if (HAL_UARTEx_SetRxFifoThreshold(&huart1, UART_RXFIFO_THRESHOLD_1_8) != HAL_OK)
{
Error_Handler();
}
if (HAL_UARTEx_DisableFifoMode(&huart1) != HAL_OK)
{
Error_Handler();
}
__HAL_UART_ENABLE_IT(&huart1,UART_IT_RXNE);
}
/**
* @brief GPIO Initialization Function
* @param None
* @retval None
*/
static void MX_GPIO_Init(void)
{
/* USER CODE BEGIN MX_GPIO_Init_1 */
/* USER CODE END MX_GPIO_Init_1 */
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
/* USER CODE BEGIN MX_GPIO_Init_2 */
/* USER CODE END MX_GPIO_Init_2 */
}
/* 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\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
Update.c
#include "Update.h"
uint32_t FirstPage = 0;
uint32_t PageError = 0;
void Write_Flash(uint8_t *data, uint16_t DataLen, uint32_t Addr)
{
uint16_t i = 0;
uint64_t Data = 0;
uint64_t temp = 0;
HAL_FLASH_Unlock();
for(i = 0; i < DataLen; i += 8)
{
Data = 0;
for(uint8_t j = 0; j < 8; j++)
{
temp = data[i + j];
Data |= temp << 8 * j;
}
if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_DOUBLEWORD, FLASH_APP_ADDR + Addr + i, Data) == HAL_OK)
{
}
/* printf("0x%16llx |", Data);
if(i % 16 == 0 && i != 0)
printf("\r\n");*/
}
HAL_FLASH_Lock();
}
static uint32_t GetPage(uint32_t Addr)
{
return (Addr - FLASH_BASE) / FLASH_PAGE_SIZE;;
}
void Write_Updata_Flag_Flash(void)
{
HAL_FLASH_Unlock();
HAL_FLASH_Program(FLASH_TYPEPROGRAM_DOUBLEWORD, FLASH_Updata_Flag_ADDR, 0x55555555);
HAL_FLASH_Lock();
}
void Erase_Updata_Flag_Flash(void)
{
FLASH_EraseInitTypeDef EraseInitStruct;
HAL_FLASH_Unlock();
FirstPage = GetPage(FLASH_Updata_Flag_ADDR);
EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES;
EraseInitStruct.Page = FirstPage;
EraseInitStruct.NbPages = 1;
if (HAL_FLASHEx_Erase(&EraseInitStruct, &PageError) != HAL_OK)
{
}
HAL_FLASH_Lock();
}
void Erase_APP_Flash(void)
{
FLASH_EraseInitTypeDef EraseInitStruct;
HAL_FLASH_Unlock();
FirstPage = GetPage(FLASH_APP_ADDR);
EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES;
EraseInitStruct.Page = FirstPage;
EraseInitStruct.NbPages = 57;
if (HAL_FLASHEx_Erase(&EraseInitStruct, &PageError) != HAL_OK)
{
}
HAL_FLASH_Lock();
}
void Read_Flash_Data(uint8_t* pBuffer, uint32_t NumToRead, uint32_t ReadAddr)
{
uint32_t i;
for (i = 0; i < NumToRead; i++)
{
*((uint8_t*)pBuffer + i) = *((uint8_t*)ReadAddr + i);
}
}
#define RX_QUEUE_LENGTH 2048
static uint8_t RxQueue[RX_QUEUE_LENGTH];
uint8_t Update_Data[1024 + 10];
static uint16_t RxQueueHead = 0;
static uint16_t RxQueueTail = 0;
typedef enum
{
RECEIVER_IDLE = 0,
RECEIVER_HEAD_H,
RECEIVER_HEAD_L,
RECEIVER_CMD,
RECEIVER_LEN_H,
RECEIVER_LEN_L,
RECEIVER_DATA,
RECEIVER_CHECK,
}RECEIVER_STATE;
typedef enum
{
UPDATE_IDLE = 0,
UPDATE_START,
UPDATE_STARTING,
UPDATE_END,
}UPDATE_STATE;
RECEIVER_STATE Receiver_State = RECEIVER_HEAD_H;
UPDATE_STATE Update_State = UPDATE_IDLE;
void OnDataReceived(uint8_t val)
{
if(((RxQueueTail + 1) % RX_QUEUE_LENGTH) != RxQueueHead) //queue is not full
{
RxQueue[RxQueueTail++] = val; //save data into queue
RxQueueTail %= RX_QUEUE_LENGTH; //queue tail++
}
}
void ClearRxQueue(void)
{
RxQueueHead = 0;
RxQueueTail = 0;
memset(RxQueue, 0, sizeof(RxQueue));
}
static uint16_t GetRxQueueLen(void)
{
return ((RxQueueTail + RX_QUEUE_LENGTH - RxQueueHead) % RX_QUEUE_LENGTH);
}
uint8_t GetRxQueueData(void)
{
uint8_t val;
val = RxQueue[RxQueueHead];
RxQueueHead = ((RxQueueHead + 1) % RX_QUEUE_LENGTH);
return val;
}
uint8_t Check_Sum(uint8_t *str, uint16_t len)
{
uint8_t sum = 0;
for(;len > 0; len--)
{
sum += *str++;
}
return sum;
}
bool Usart_Data_Handler(void)
{
static uint8_t Data;
static uint8_t Cmd;
static uint8_t Check;
static uint8_t Send_Data[10];
static uint16_t Update_Pack_Num;
static uint16_t Update_Pack_Num_Temp;
static uint32_t Update_Data_Len;
static uint32_t Write_Date_Len;
static uint16_t Receive_Data_Len;
static uint16_t Receive_Data_Count;
while(GetRxQueueLen() > 0)
{
Data = GetRxQueueData();
if(Receiver_State == RECEIVER_HEAD_H)
{
if(Data == 0x55)
{
Receiver_State++;
}
}
else if(Receiver_State == RECEIVER_HEAD_L)
{
if(Data == 0x55)
{
Receiver_State++;
}
}
else if(Receiver_State == RECEIVER_CMD)
{
Receiver_State++;
Receive_Data_Len = 0;
Receive_Data_Count = 0;
Cmd = Data;
if(Cmd == 0x00)
{
printf("Cmd == 0x00\r\n");
}else if(Cmd == 0x01)
{
Update_State = UPDATE_START;
Update_Pack_Num = 0;
Write_Date_Len = 0;
printf("Update_State UPDATE_START\r\n");
}
else if(Cmd == 0x02)
{
Update_State = UPDATE_STARTING;
printf("Update_State UPDATE_STARTING\r\n");
}
else if(Cmd == 0x03)
{
Update_State = UPDATE_END;
printf("Update_State UPDATE_END\r\n");
}
}
else if(Receiver_State == RECEIVER_LEN_H)
{
Receiver_State++;
Receive_Data_Len |= Data << 8;
}
else if(Receiver_State == RECEIVER_LEN_L)
{
Receiver_State++;
Receive_Data_Len |= Data;
if(Receive_Data_Len == 0)
{
Receiver_State = RECEIVER_CHECK;
}
}
else if(Receiver_State == RECEIVER_DATA)
{
Update_Data[Receive_Data_Count++] = Data;
if(Cmd == 0x01)
{
if(Receive_Data_Count == 4)
{
Update_Data_Len = 0;
Update_Data_Len |= Update_Data[0] << 24;
Update_Data_Len |= Update_Data[1] << 16;
Update_Data_Len |= Update_Data[2] << 8;
Update_Data_Len |= Update_Data[3];
}
}
else if(Cmd == 0x02)
{
if(Receive_Data_Count == 2)
{
Update_Pack_Num_Temp = 0;
Update_Pack_Num_Temp |= Update_Data[0] << 8;
Update_Pack_Num_Temp |= Update_Data[1];
}
}
if(Receive_Data_Count == Receive_Data_Len)
{
Receiver_State++;
}
}
else if(Receiver_State == RECEIVER_CHECK)
{
Receiver_State = RECEIVER_HEAD_H;
Check = Data;
Send_Data[0] = 0x55;
Send_Data[1] = 0x55;
Send_Data[2] = Cmd;
Send_Data[3] = 0x00;
if(Update_State == UPDATE_START)
{
Erase_APP_Flash();
printf("Erase_APP_Flash\r\n");
printf("Update_Data_Len = %d\r\n", Update_Data_Len);
Send_Data[4] = 0x00;
Send_Data[5] = 0x00;
Uart_Send_Data(Send_Data, 6);
}
else if(Update_State == UPDATE_STARTING)
{
if(Update_Pack_Num_Temp == Update_Pack_Num)
{
Check = Check_Sum(Update_Data, Receive_Data_Len);
if(Check == Data)
{
Update_Pack_Num++;
Write_Flash(&Update_Data[2], Receive_Data_Len - 2, Write_Date_Len);
Write_Date_Len += Receive_Data_Len - 2;
printf("Receive Update_Pack_Num = %d\r\n", Update_Pack_Num_Temp);
printf("Write_Date_Len = %d, Update_Data_Len = %d\r\n", Write_Date_Len, Update_Data_Len);
}
else
{
printf("Check Error Check = %d, ReceCheck = %d \r\n", Check, Data);
}
}
if(Write_Date_Len == Update_Data_Len)
{
Send_Data[2] = 0x03;
Send_Data[3] = 0x00;
Send_Data[4] = 0x00;
Send_Data[5] = 0x00;
Uart_Send_Data(Send_Data, 6);
Erase_Updata_Flag_Flash();
Write_Updata_Flag_Flash();
printf("Upgrade successfully \r\n");
NVIC_SystemReset();
}
else
{
Send_Data[4] = 0x02;
Send_Data[5] = Update_Pack_Num >> 8;
Send_Data[6] = Update_Pack_Num;
Send_Data[7] = Check_Sum(&Send_Data[5], 2);
Uart_Send_Data(Send_Data, 8);
}
}
else if(Update_State == UPDATE_END)
{
Send_Data[4] = 0x00;
Send_Data[5] = 0x00;
Uart_Send_Data(Send_Data, 6);
}
}
}
}
void Usart_Get_Data_Handler(void)
{
if(!Usart_Data_Handler())
{
return;
}
}
Update.h
#ifndef __UPDATE_H
#define __UPDATE_H
#include "main.h"
#include
#include
#include
#define FLASH_Page_Size (2048)
#define FLASH_Updata_Flag_ADDR (0x08000000 + 6 * FLASH_Page_Size)
#define FLASH_APP_ADDR (0x08000000 + 7 * FLASH_Page_Size)
void Erase_APP_Flash(void);
void Erase_Updata_Flag_Flash(void);
void Write_Flash(uint8_t *data, uint16_t DataLen, uint32_t Addr);
void Read_Flash_Data(uint8_t* pBuffer, uint32_t NumToRead, uint32_t ReadAddr);
void ClearRxQueue(void);
void OnDataReceived(uint8_t val);
bool Usart_Data_Handler(void);
#endif
stm32g0xx_it.c
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file stm32g0xx_it.c
* @brief Interrupt Service Routines.
******************************************************************************
* @attention
*
* Copyright (c) 2023 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 "stm32g0xx_it.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN TD */
/* USER CODE END TD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* 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 -----------------------------------------------*/
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/* External variables --------------------------------------------------------*/
extern UART_HandleTypeDef huart1;
/* USER CODE BEGIN EV */
/* USER CODE END EV */
/******************************************************************************/
/* Cortex-M0+ Processor Interruption and Exception Handlers */
/******************************************************************************/
/**
* @brief This function handles Non maskable interrupt.
*/
void NMI_Handler(void)
{
/* USER CODE BEGIN NonMaskableInt_IRQn 0 */
/* USER CODE END NonMaskableInt_IRQn 0 */
/* USER CODE BEGIN NonMaskableInt_IRQn 1 */
while (1)
{
}
/* USER CODE END NonMaskableInt_IRQn 1 */
}
/**
* @brief This function handles Hard fault interrupt.
*/
void HardFault_Handler(void)
{
/* USER CODE BEGIN HardFault_IRQn 0 */
/* USER CODE END HardFault_IRQn 0 */
while (1)
{
/* USER CODE BEGIN W1_HardFault_IRQn 0 */
/* USER CODE END W1_HardFault_IRQn 0 */
}
}
/**
* @brief This function handles System service call via SWI instruction.
*/
void SVC_Handler(void)
{
/* USER CODE BEGIN SVC_IRQn 0 */
/* USER CODE END SVC_IRQn 0 */
/* USER CODE BEGIN SVC_IRQn 1 */
/* USER CODE END SVC_IRQn 1 */
}
/**
* @brief This function handles Pendable request for system service.
*/
void PendSV_Handler(void)
{
/* USER CODE BEGIN PendSV_IRQn 0 */
/* USER CODE END PendSV_IRQn 0 */
/* USER CODE BEGIN PendSV_IRQn 1 */
/* USER CODE END PendSV_IRQn 1 */
}
/**
* @brief This function handles System tick timer.
*/
void SysTick_Handler(void)
{
/* USER CODE BEGIN SysTick_IRQn 0 */
/* USER CODE END SysTick_IRQn 0 */
HAL_IncTick();
/* USER CODE BEGIN SysTick_IRQn 1 */
/* USER CODE END SysTick_IRQn 1 */
}
/******************************************************************************/
/* STM32G0xx Peripheral Interrupt Handlers */
/* Add here the Interrupt Handlers for the used peripherals. */
/* For the available peripheral interrupt handler names, */
/* please refer to the startup file (startup_stm32g0xx.s). */
/******************************************************************************/
/**
* @brief This function handles USART1 global interrupt / USART1 wake-up interrupt through EXTI line 25.
*/
#include "stdio.h"
#include "Update.h"
uint8_t pData[1];
void USART1_IRQHandler(void)
{
HAL_UART_IRQHandler(&huart1);
UART_Start_Receive_IT(&huart1, pData, 1);
OnDataReceived(pData[0]);
}
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
上位机升级工具:升级工具
单Bank OTA升级:STM32G071 APP (二):跳转链接