STM32F103C8T6 FLASH 标准库程序
时间: 2024-04-25 09:05:07 浏览: 23
以下是 STM32F103C8T6 的 FLASH 标准库程序,可以实现读取、擦除、编程等操作:
```c
#include "stm32f10x.h"
#define FLASH_PAGE_SIZE 0x400 // FLASH 一页的大小,1KB
void FLASH_Write(uint32_t addr, uint16_t *data, uint16_t count)
{
uint32_t i, j, data32;
FLASH_Unlock(); // 解锁 FLASH,使能写操作
// 擦除 FLASH 页
FLASH_ErasePage(addr);
// 编程 FLASH
for (i = 0, j = 0; i < count; i++, j += 2)
{
data32 = (uint32_t)(data[i]);
data32 |= ((uint32_t)(data[i + 1])) << 16;
FLASH_ProgramWord(addr + j, data32);
}
FLASH_Lock(); // 锁定 FLASH,禁止写操作
}
uint32_t FLASH_Read(uint32_t addr, uint16_t *data, uint16_t count)
{
uint32_t i, j, data32;
for (i = 0, j = 0; i < count; i++, j += 2)
{
data32 = *(volatile uint32_t *)(addr + j);
data[i] = (uint16_t)(data32 & 0xFFFF);
data[i + 1] = (uint16_t)(data32 >> 16);
}
return i;
}
void FLASH_ErasePage(uint32_t addr)
{
FLASH_Status status;
FLASH_ClearFlag(FLASH_FLAG_BSY | FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR);
status = FLASH_ErasePage(addr);
if (status != FLASH_COMPLETE)
{
// 擦除失败,处理错误
}
}
void FLASH_ProgramWord(uint32_t addr, uint32_t data)
{
FLASH_Status status;
FLASH_ClearFlag(FLASH_FLAG_BSY | FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR);
status = FLASH_ProgramWord(addr, data);
if (status != FLASH_COMPLETE)
{
// 编程失败,处理错误
}
}
void FLASH_Unlock(void)
{
if ((FLASH->CR & FLASH_CR_LOCK) != 0)
{
FLASH->KEYR = 0x45670123;
FLASH->KEYR = 0xCDEF89AB;
}
}
void FLASH_Lock(void)
{
FLASH->CR |= FLASH_CR_LOCK;
}
```
上述程序中的 `FLASH_Write` 函数实现了向指定地址写入数据的功能,输入参数包括写入地址 `addr`、写入数据指针 `data` 和数据长度 `count`。具体实现过程包括解锁 FLASH、擦除 FLASH 页、编程 FLASH 和锁定 FLASH 等步骤。另外,还提供了 `FLASH_Read`、`FLASH_ErasePage`、`FLASH_ProgramWord`、`FLASH_Unlock` 和 `FLASH_Lock` 等函数,分别用于读取数据、擦除 FLASH 页、编程 FLASH、解锁 FLASH 和锁定 FLASH 等操作。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)