| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108 |
- #include "hal_flash.h"
- #include "stm32f1xx_hal_flash_ex.h"
- #include "stm32f1xx_hal_flash.h"
- #include "stdint.h"
- #include "string.h"
- #include "sys_log.h"
- static uint8_t _flash_write_word(uint32_t address, uint32_t value);
- static uint8_t _flash_sector_erase(uint32_t sector);
- uint8_t HAL_FlashInit(void *args)
- {
- return 0;
- }
- uint8_t HAL_FlashWriteBytes(uint32_t addr, uint8_t *buf, uint16_t size)
- {
- int w_size = size >> 2;
- int r_w_size = size - (w_size << 2);
- int i = 0, offset = 0, offset_w;
- int w_data;
- for (; i < w_size; i++)
- {
- w_data = *(int *)(buf + offset);
- if (_flash_write_word(addr + offset, w_data))
- {
- return 1;
- }
- offset += 4;
- }
- if (r_w_size)
- {
- w_data = 0;
- offset_w = 0;
- for (i = 0; i < r_w_size; i++)
- {
- w_data = (w_data) | (*(buf + offset + i) << offset_w);
- offset_w += 8;
- }
- if (_flash_write_word(addr + offset, w_data))
- {
- return 1;
- }
- }
- return 0;
- }
- uint8_t HAL_FlashReadBytes(uint32_t addr, uint8_t *buf, uint16_t size)
- {
- memcpy(buf, (const uint8_t *)addr, size);
- return 0;
- }
- uint8_t HAL_FlashSectorErase(uint32_t addr)
- {
- return (_flash_sector_erase(addr));
- }
- static uint8_t _flash_sector_erase(uint32_t sector)
- {
- FLASH_EraseInitTypeDef pEraseInit;
- HAL_StatusTypeDef status = HAL_OK;
- uint32_t PageError = 0;
- int i;
- pEraseInit.TypeErase = FLASH_TYPEERASE_PAGES;
- pEraseInit.Banks = FLASH_BANK_1;
- pEraseInit.PageAddress = sector;
- pEraseInit.NbPages = 1;
- HAL_FLASH_Unlock();
- for (i = 0; i < 3; i++)
- {
- status = HAL_FLASHEx_Erase(&pEraseInit, &PageError);
- if (HAL_OK == status)
- {
- break;
- }
- }
- HAL_FLASH_Lock();
- if (status != HAL_OK)
- {
- /* Error occurred while page erase */
- return FLASHIF_ERASEKO;
- }
- return FLASHIF_OK;
- }
- static uint8_t _flash_write_word(uint32_t address, uint32_t value)
- {
- HAL_StatusTypeDef status = HAL_OK;
- HAL_FLASH_Unlock();
- status = HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, address, value);
- HAL_FLASH_Lock();
- if (status != HAL_OK)
- {
- /* Error occurred while page erase */
- return FLASHIF_WRITING_ERROR;
- }
- return FLASHIF_OK;
- }
|