Bootstrap

stm32 g0 使用内部flash读写

 个别芯片存储空间为32k,注意使用范围,并且利用debug或者.map文件,避开程序占用的页。

g0hal库和其他系列有些不同,根据官方例程修改。

GO30F6P6是 32k FLASH.基地址0x8000000,长度0x8000。即0x8000000-0x8008000。在keil配置的Target的rom和debug中flash选择可看到

具体计算过程省略

写FLASH


/**
 * @brief       获取 地址Addr 在 Flash中式第几页。根据每页大小2k 
 * @param       Addr    开头地址
 * @retval      FLASH页数
 */
static uint32_t GetPage(uint32_t Addr)
{
    uint32_t page = 0;
    page = (Addr-FLASH_BASE) / FLASH_PAGE_SIZE;
    return page;
}

/**
 * @brief       擦除FLASH
 * @param       s_addr    开头地址
 * @param       end_addr    结束地址
 */
 void Erase_Flash(uint32_t s_addr,uint32_t end_addr) 
{
    uint32_t SectorError=0,FirstPage,NbOfPages;
    FLASH_EraseInitTypeDef E_FLASH;
    
      /* Get the 1st page to erase */
     FirstPage = GetPage(s_addr);

  /* Get the number of pages to erase from 1st page */
    NbOfPages = GetPage(end_addr) - FirstPage + 1;

    E_FLASH.TypeErase = FLASH_TYPEERASE_PAGES;
    E_FLASH.Page = FirstPage;
    E_FLASH.NbPages =NbOfPages;
    if(HAL_FLASHEx_Erase(&E_FLASH,&SectorError) != HAL_OK) {

    }

}


/**
 * @brief       写Flash,写之前需要擦除整页flash,修改宏定义
 * @param       start_address    开头地址
 *  @param      end_address   结束地址
 * @param       *buf       写入数据
 * @param       length     写入字节数据个数
 */
void Write_Flash(uint32_t start_address,uint32_t end_address,uint64_t  *buf, uint16_t length)
{
    uint64_t data = 0;
    uint16_t i;
    if(start_address < STM32_FLASH_BASE || (start_address >= (STM32_FLASH_BASE + STM_SECTOR_SIZE * STM32_FLASH_SIZE)))    
    {
         //长度不在范围
       return;
    }

    
    HAL_FLASH_Unlock();//解锁flash	 
    Erase_Flash(start_address , end_address);   //擦除Flash

	for(i=0;i<length;i++)
	{
        data = 0;
        data=buf[i];
        if(HAL_FLASH_Program(FLASH_TYPEPROGRAM_DOUBLEWORD,start_address,data) != HAL_OK) 
        {
            HAL_FLASH_Lock();
            return;
        }            
        start_address += 8;
	}  

    HAL_FLASH_Lock();//上锁

}

读FLASH

uint32_t ST_Flash_Read(uint32_t R_Addr)

{

     //直接读地址,可以读取其他类型,。

    return *(volatile uint32_t *)R_Addr;

}

头文件

#ifndef __HAL_FLASH_H
#define __HAL_FLASH_H

#include "main.h"


#define __IO    volatile 
typedef __IO uint16_t vu16;
 
#define STM32_FLASH_SIZE 	32 	 	//所选STM32的FLASH容量大小(单位为K)
#define STM_SECTOR_SIZE	    2048    //2K字节

#define STM32_FLASH_BASE    0x08000000 		//STM32 FLASH的起始地址

//开始28672 = 7000,结束77FF
#define FLASH_USER_START_ADDR 0x08007000           /* 第13页 Start @ of user Flash area */
#define FLASH_USER_END_ADDR   0x080077FF         /* 第13页 End @ of user Flash area */



 void Erase_Flash(uint32_t s_addr,uint32_t end_addr) ;
void Write_Flash(uint32_t start_address,uint32_t end_address,uint64_t  *buf, uint16_t length);
uint32_t ST_Flash_Read(uint32_t R_Addr);
// void KaiJ_Read_FLASH();

// extern uint64_t set_Flashdat;

#endif

;