CM_DOG/User/bsp/flash.c
2025-06-24 10:28:20 +08:00

64 lines
2.4 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/* Includes ----------------------------------------------------------------- */
#include "bsp/flash.h"
#include <main.h>
#include <string.h>
/* Private define ----------------------------------------------------------- */
/* Private macro ------------------------------------------------------------ */
/* Private typedef ---------------------------------------------------------- */
/* Private variables -------------------------------------------------------- */
/* Private function -------------------------------------------------------- */
/* Exported functions ------------------------------------------------------- */
/// @brief 擦除指定的Flash扇区
/// @param sector 扇区编号0~7对应Bank1的扇区
void BSP_Flash_EraseSector(uint32_t sector) {
FLASH_EraseInitTypeDef flash_erase;
uint32_t sector_error;
// 仅支持sector 0~7属于Bank1
if (sector < 8) {
flash_erase.TypeErase = FLASH_TYPEERASE_SECTORS;
flash_erase.Banks = FLASH_BANK_1;
flash_erase.Sector = sector;
flash_erase.NbSectors = 1;
flash_erase.VoltageRange = FLASH_VOLTAGE_RANGE_3;
HAL_FLASH_Unlock();
FLASH_WaitForLastOperation(HAL_MAX_DELAY, FLASH_BANK_1);
HAL_FLASHEx_Erase(&flash_erase, &sector_error);
HAL_FLASH_Lock();
}
}
/// @brief 写入指定地址的字节数据到Flash
/// @param address Flash地址必须是32字节对齐
/// @param buf 指向要写入的数据缓冲区
/// @param len 要写入的字节数必须是32的倍数
void BSP_Flash_WriteBytes(uint32_t address, const uint8_t *buf, size_t len) {
HAL_FLASH_Unlock();
while (len > 0) {
uint8_t flash_word[32];
size_t write_len = (len >= 32) ? 32 : len;
memset(flash_word, 0xFF, 32);
memcpy(flash_word, buf, write_len);
// 地址需32字节对齐
uint32_t aligned_addr = address & ~0x1F;
HAL_FLASH_Program(FLASH_TYPEPROGRAM_FLASHWORD, aligned_addr, (uint32_t)flash_word);
address += write_len;
buf += write_len;
len -= write_len;
}
HAL_FLASH_Lock();
}
/// @brief 从指定地址读取字节数据到缓冲区
/// @param address Flash地址必须是32字节对齐
/// @param buf 指向要读取数据的缓冲区
/// @param len 要读取的字节数必须是32的倍数
void BSP_Flash_ReadBytes(uint32_t address, void *buf, size_t len) {
memcpy(buf, (void *)address, len);
}