stm32 hal 读写保护代码 用中文注释
时间: 2023-09-14 08:08:44 浏览: 72
以下是使用STM32 HAL库实现读写保护的示例代码,附带中文注释:
```
#include "stm32f1xx_hal.h"
#include <string.h>
// 定义读写保护的扇区
#define FLASH_WRITE_PROTECTION_SECTORS OB_WRP_SECTOR_0 | OB_WRP_SECTOR_1
// 定义要写入Flash的数据
uint32_t data_to_write[] = {0x12345678, 0x9ABCDEF0};
int main(void)
{
// 初始化HAL库
HAL_Init();
// 解锁Flash
HAL_FLASH_Unlock();
// 配置读写保护
FLASH_OBProgramInitTypeDef OBInit;
OBInit.OptionType = OPTIONBYTE_WRP;
OBInit.Banks = FLASH_BANK_1;
OBInit.WRPSector = FLASH_WRITE_PROTECTION_SECTORS;
HAL_FLASHEx_OBProgram(&OBInit);
// 锁定Flash
HAL_FLASH_Lock();
// 写入数据到Flash
HAL_FLASH_Unlock();
for(int i=0; i<sizeof(data_to_write)/sizeof(uint32_t); i++) {
HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, FLASH_BASE + i*4, data_to_write[i]);
}
HAL_FLASH_Lock();
// 读取Flash中的数据
uint32_t read_data[sizeof(data_to_write)/sizeof(uint32_t)];
memcpy(read_data, (uint32_t*)FLASH_BASE, sizeof(read_data));
// 循环打印读取到的数据
while(1) {
for(int i=0; i<sizeof(read_data)/sizeof(uint32_t); i++) {
printf("data[%d]: 0x%08X\r\n", i, read_data[i]);
}
HAL_Delay(1000);
}
}
```
阅读全文