void flash_erase(uint32_t sector) { uint32_t SectorError = 0; // unlock HAL_FLASH_Unlock(); // Clear pending flags (if any) __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR); // erase the sector(s) FLASH_EraseInitTypeDef EraseInitStruct; EraseInitStruct.TypeErase = TYPEERASE_SECTORS; EraseInitStruct.VoltageRange = VOLTAGE_RANGE_3; // voltage range needs to be 2.7V to 3.6V EraseInitStruct.Sector = sector; EraseInitStruct.NbSectors = 1; if (HAL_FLASHEx_Erase(&EraseInitStruct, &SectorError) != HAL_OK) { // error occurred during sector erase HAL_FLASH_Lock(); // lock the flash __fatal_error(); } HAL_FLASH_Lock(); // lock the flash }
/** * @brief Erase Access Point parameters from FLASH * @param None * @retval System_Status_t (MODULE_SUCCESS/MODULE_ERROR) */ System_Status_t ResetSSIDPasswordInMemory(void) { /* Reset Calibration Values in FLASH */ System_Status_t status = MODULE_ERROR; /* Erase First Flash sector */ FLASH_EraseInitTypeDef EraseInitStruct; uint32_t SectorError = 0; EraseInitStruct.TypeErase = TYPEERASE_SECTORS; EraseInitStruct.VoltageRange = VOLTAGE_RANGE_3; EraseInitStruct.Sector = BLUEMSYS_FLASH_SECTOR; EraseInitStruct.NbSectors = 1; /* Unlock the Flash to enable the flash control register access *************/ HAL_FLASH_Unlock(); if (HAL_FLASHEx_Erase(&EraseInitStruct, &SectorError) != HAL_OK){ /* Error occurred while sector erase. User can add here some code to deal with this error. SectorError will contain the faulty sector and then to know the code error on this sector, user can call function 'HAL_FLASH_GetError()' FLASH_ErrorTypeDef errorcode = HAL_FLASH_GetError(); */ printf("\n\rError while erasing FLASH memory"); } else { status = MODULE_SUCCESS; } /* Lock the Flash to disable the flash control register access (recommended to protect the FLASH memory against possible unwanted operation) *********/ HAL_FLASH_Lock(); return status; }
/** * @brief This function does an erase of all user flash area * @param StartSector: start of user flash area * @retval 0: user flash area successfully erased * 1: error occurred */ int8_t FLASH_If_Erase(uint32_t StartSector) { uint32_t FlashAddress; FlashAddress = StartSector; /* Device voltage range supposed to be [2.7V to 3.6V], the operation will be done by word */ if (FlashAddress <= (uint32_t) USER_FLASH_LAST_PAGE_ADDRESS) { FLASH_EraseInitTypeDef FLASH_EraseInitStruct; uint32_t sectornb = 0; FLASH_EraseInitStruct.TypeErase = FLASH_TYPEERASE_SECTORS; FLASH_EraseInitStruct.Sector = FLASH_SECTOR_5; FLASH_EraseInitStruct.NbSectors = 7; FLASH_EraseInitStruct.VoltageRange = FLASH_VOLTAGE_RANGE_3; if (HAL_FLASHEx_Erase(&FLASH_EraseInitStruct, §ornb) != HAL_OK) return (1); } else { return (1); } return (0); }
void flash_erase(uint32_t flash_dest, const uint32_t *src, uint32_t num_word32) { // check there is something to write if (num_word32 == 0) { return; } // unlock HAL_FLASH_Unlock(); // Clear pending flags (if any) __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR); // erase the sector(s) FLASH_EraseInitTypeDef EraseInitStruct; EraseInitStruct.TypeErase = TYPEERASE_SECTORS; EraseInitStruct.VoltageRange = VOLTAGE_RANGE_3; // voltage range needs to be 2.7V to 3.6V EraseInitStruct.Sector = flash_get_sector_info(flash_dest, NULL, NULL); EraseInitStruct.NbSectors = flash_get_sector_info(flash_dest + 4 * num_word32 - 1, NULL, NULL) - EraseInitStruct.Sector + 1; uint32_t SectorError = 0; if (HAL_FLASHEx_Erase(&EraseInitStruct, &SectorError) != HAL_OK) { // error occurred during sector erase HAL_FLASH_Lock(); // lock the flash return; } }
/** * @brief Erases the required FLASH Sectors. * @param Address: Start address for erasing data * @retval 0: Erase sectors done with success * 1: Erase error */ uint32_t FLASH_If_EraseSectors(uint32_t Address) { /* Erase the user Flash area (area defined by APPLICATION_ADDRESS and USER_FLASH_LAST_PAGE_ADDRESS) ****/ if(Address <= (uint32_t) USER_FLASH_LAST_PAGE_ADDRESS) { /* Get the 1st sector to erase */ FirstSector = FLASH_If_GetSectorNumber(Address); /* Get the number of sector to erase from 1st sector */ NbOfSectors = FLASH_If_GetSectorNumber(USER_FLASH_LAST_PAGE_ADDRESS) - FirstSector + 1; FLASH_EraseInitStruct.TypeErase = FLASH_TYPEERASE_SECTORS; FLASH_EraseInitStruct.Sector = FirstSector; FLASH_EraseInitStruct.NbSectors = NbOfSectors; FLASH_EraseInitStruct.VoltageRange = FLASH_VOLTAGE_RANGE_3; if(HAL_FLASHEx_Erase(&FLASH_EraseInitStruct, &SectorError) != HAL_OK) return (1); } else { return (1); } return (0); }
void ErasePage(uint32_t pageAddress) { FLASH_EraseInitTypeDef EraseInitStruct; uint32_t FirstPage = 0, NbOfPages = 0, BankNumber = 0, PAGEError = 0; /* Unlock the Flash to enable the flash control register access */ HAL_FLASH_Unlock(); /* Clear OPTVERR bit set on virgin samples */ __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_OPTVERR); /* Get the 1st page to erase */ FirstPage = GetPage(pageAddress); /* Get the number of pages to erase from 1st page */ NbOfPages = 1; /* Get the bank */ BankNumber = GetBank(pageAddress); /* Fill EraseInit structure*/ EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES; EraseInitStruct.Banks = BankNumber; EraseInitStruct.Page = FirstPage; EraseInitStruct.NbPages = NbOfPages; HAL_FLASHEx_Erase(&EraseInitStruct, &PAGEError); HAL_FLASH_Lock(); }
/** * @brief Erases sector. * @param Add: Address of sector to be erased. * @retval 0 if operation is successful, MAL_FAIL else. */ uint16_t Flash_If_Erase(uint32_t Add) { uint32_t startsector = 0, sectorerror = 0, nbofsectors = 0; /* Variable contains Flash operation status */ HAL_StatusTypeDef status; FLASH_EraseInitTypeDef eraseinitstruct; /* Get the number of sector */ startsector = GetSector(Add); /* Get the number of sector to erase from the start sector: max number of sectors - value of Initial sector */ nbofsectors = (USBD_DFU_MAX_NB_OF_SECTORS - startsector); eraseinitstruct.TypeErase = FLASH_TYPEERASE_SECTORS; eraseinitstruct.Banks = 0; eraseinitstruct.Sector = startsector; eraseinitstruct.NbSectors = nbofsectors; eraseinitstruct.VoltageRange = FLASH_VOLTAGE_RANGE_3; status = HAL_FLASHEx_Erase(&eraseinitstruct, §orerror); if (status != HAL_OK) { return 1; } return 0; }
/** * @brief Erase flash block * @note Block is the same thing as page in terms of stm32 lib: * it's minimal erasable chunk of flash memory * * @param dev * @param block * * @return Error code */ static int stm32f3_flash_erase_block(struct flash_dev *dev, uint32_t block) { int err; uint32_t page_err; FLASH_EraseInitTypeDef erase_struct; if (!stm32f3_flash_check_block(dev, block)) { return -EINVAL; } HAL_FLASH_Unlock(); erase_struct = (FLASH_EraseInitTypeDef) { .TypeErase = TYPEERASE_PAGES, .PageAddress = dev->start + block * STM32F3_FLASH_PAGE_SIZE, .NbPages = 1, }; err = HAL_FLASHEx_Erase(&erase_struct, &page_err); /* TODO check errcode */ /* Lock to prevent unwanted operations with flash memory */ HAL_FLASH_Lock(); return err; } static int stm32f3_flash_read(struct flash_dev *dev, uint32_t base, void* data, size_t len) { size_t rlen = min(len, dev->end - dev->start + base); /* read can be unaligned */ memcpy(data, (void *) dev->start + base, rlen); return rlen; }
/** * @brief This function does an erase of all user flash area * @param StartSector: start of user flash area * @retval 0: user flash area successfully erased * 1: error occurred */ uint32_t FLASH_If_Erase(uint32_t StartSector) { uint32_t UserStartSector; uint32_t SectorError; FLASH_EraseInitTypeDef pEraseInit; /* Unlock the Flash to enable the flash control register access *************/ FLASH_If_Init(); /* Get the sector where start the user flash area */ UserStartSector = GetSector(APPLICATION_ADDRESS); pEraseInit.TypeErase = TYPEERASE_SECTORS; pEraseInit.Sector = UserStartSector; pEraseInit.NbSectors = 6; pEraseInit.VoltageRange = VOLTAGE_RANGE_3; if (HAL_FLASHEx_Erase(&pEraseInit, &SectorError) != HAL_OK) { /* Error occurred while page erase */ return (1); } return (0); }
/** * @brief This function does an erase of all user flash area * @param start: start of user flash area * @retval FLASHIF_OK : user flash area successfully erased * FLASHIF_ERASEKO : error occurred */ uint32_t FLASH_If_Erase(uint32_t start) { uint32_t NbrOfPages = 0; uint32_t PageError = 0; FLASH_EraseInitTypeDef pEraseInit; HAL_StatusTypeDef status = HAL_OK; /* Unlock the Flash to enable the flash control register access *************/ HAL_FLASH_Unlock(); /* Get the sector where start the user flash area */ NbrOfPages = (USER_FLASH_END_ADDRESS - start)/FLASH_PAGE_SIZE; pEraseInit.TypeErase = FLASH_TYPEERASE_PAGES; pEraseInit.PageAddress = start; pEraseInit.NbPages = NbrOfPages; status = HAL_FLASHEx_Erase(&pEraseInit, &PageError); /* Lock the Flash to disable the flash control register access (recommended to protect the FLASH memory against possible unwanted operation) *********/ HAL_FLASH_Lock(); if (status != HAL_OK) { /* Error occurred while page erase */ return FLASHIF_ERASEKO; } return FLASHIF_OK; }
static ssize_t stm32_flash_bdev_erase(struct bdev *bdev, off_t offset, size_t len) { LTRACEF("dev %p, offset 0x%llx, len 0x%zx\n", bdev, offset, len); ssize_t total_erased = 0; HAL_FLASH_Unlock(); while (len > 0) { uint32_t sector = 0; off_t sector_offset = 0; off_t next_offset = 0; if (offset_to_sector(offset, §or, §or_offset, &next_offset) < 0) return ERR_INVALID_ARGS; FLASH_EraseInitTypeDef erase; erase.TypeErase = FLASH_TYPEERASE_SECTORS; erase.Sector = sector; erase.NbSectors = 1; erase.VoltageRange = FLASH_VOLTAGE_RANGE_3; // XXX LTRACEF("erase params: sector %u, num_sectors %u, next_offset 0x%llx\n", erase.Sector, erase.NbSectors, next_offset); if (1) { uint32_t sector_error; HAL_StatusTypeDef err = HAL_FLASHEx_Erase(&erase, §or_error); if (err != HAL_OK) { TRACEF("error starting erase operation, sector error %u\n", sector_error); total_erased = ERR_IO; break; } err = FLASH_WaitForLastOperation(HAL_MAX_DELAY); if (err != HAL_OK) { TRACEF("error waiting for erase operation to end, hal error %u\n", HAL_FLASH_GetError()); total_erased = ERR_IO; break; } // invalidate the cache on this region arch_invalidate_cache_range(FLASHAXI_BASE + sector_offset, next_offset - sector_offset); } // move to the next erase boundary total_erased += next_offset - sector_offset; off_t erased_bytes = next_offset - offset; if (erased_bytes >= len) break; len -= erased_bytes; offset = next_offset; } HAL_FLASH_Lock(); return total_erased; }
static void stm32f4_flash_erase_sector_id(int sector_id) { FLASH_EraseInitTypeDef eraseinit; uint32_t SectorError; eraseinit.TypeErase = FLASH_TYPEERASE_SECTORS; eraseinit.Banks = 0; eraseinit.Sector = sector_id; eraseinit.NbSectors = 1; eraseinit.VoltageRange = FLASH_VOLTAGE_RANGE_1; HAL_FLASHEx_Erase(&eraseinit, &SectorError); }
static int stm32f3_flash_erase_sector(const struct hal_flash *dev, uint32_t sector_address) { FLASH_EraseInitTypeDef erase; int rc = -1; uint32_t errorPage = -1; erase.TypeErase = FLASH_TYPEERASE_PAGES; erase.PageAddress = sector_address; erase.NbPages = 1; HAL_FLASH_Unlock(); if (HAL_OK == HAL_FLASHEx_Erase(&erase, &errorPage)) { rc = 0; } HAL_FLASH_Lock(); return rc; }
int flash_erase(uint32_t start_addr, uint32_t size) { FLASH_EraseInitTypeDef EraseInitStruct; uint32_t FirstPage = 0, NbOfPages = 0, BankNumber = 0, PAGEError = 0; uint32_t end_addr = start_addr + size; /* Unlock the Flash to enable the flash control register access *************/ HAL_FLASH_Unlock(); /* Erase the user Flash area */ /* Clear OPTVERR bit set on virgin samples */ __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_OPTVERR); /* Get the 1st page to erase */ FirstPage = GetPage(start_addr); /* Get the number of pages to erase from 1st page */ NbOfPages = GetPage(end_addr) - FirstPage + 1; /* Get the bank */ BankNumber = GetBank(start_addr); /* Fill EraseInit structure*/ EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES; EraseInitStruct.Banks = BankNumber; EraseInitStruct.Page = FirstPage; EraseInitStruct.NbPages = NbOfPages; /* Note: If an erase operation in Flash memory also concerns data in the data or instruction cache, you have to make sure that these data are rewritten before they are accessed during code execution. If this cannot be done safely, it is recommended to flush the caches by setting the DCRST and ICRST bits in the FLASH_CR register. */ if (HAL_FLASHEx_Erase(&EraseInitStruct, &PAGEError) != HAL_OK) { /* Error occurred while page erase. User can add here some code to deal with this error. PAGEError will contain the faulty page and then to know the code error on this page, user can call function 'HAL_FLASH_GetError()' */ /* Infinite loop */ while (1) { } } return 0; }
/** Erase one sector starting at defined address * * The address should be at sector boundary. This function does not do any check for address alignments * @param obj The flash object * @param address The sector starting address * @return 0 for success, -1 for error */ int32_t flash_erase_sector(flash_t *obj, uint32_t address) { uint32_t FirstPage = 0, BankNumber = 0; uint32_t PAGEError = 0; FLASH_EraseInitTypeDef EraseInitStruct; int32_t status = 0; if ((address >= (FLASH_BASE + FLASH_SIZE)) || (address < FLASH_BASE)) { return -1; } if (flash_unlock() != HAL_OK) { return -1; } /* Clear OPTVERR bit set on virgin samples */ __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_OPTVERR); /* Get the 1st page to erase */ FirstPage = GetPage(address); /* MBED HAL erases 1 page / sector at a time */ /* Get the bank */ BankNumber = GetBank(address); /* Fill EraseInit structure*/ EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES; EraseInitStruct.Banks = BankNumber; EraseInitStruct.Page = FirstPage; EraseInitStruct.NbPages = 1; /* Note: If an erase operation in Flash memory also concerns data in the data or instruction cache, you have to make sure that these data are rewritten before they are accessed during code execution. If this cannot be done safely, it is recommended to flush the caches by setting the DCRST and ICRST bits in the FLASH_CR register. */ if (HAL_FLASHEx_Erase(&EraseInitStruct, &PAGEError) != HAL_OK) { status = -1; } flash_lock(); return status; }
void flash_erase(uint32_t flash_user_start_addr,uint32_t flash_user_end_addr) { uint32_t NbOfPages = 0; /* Get the number of sector to erase from 1st sector*/ NbOfPages = (flash_user_end_addr - flash_user_start_addr + 1) >> 7;//Ò»¸öpage 128 ×Ö½Ú = 2>>7 /* Fill EraseInit structure*/ EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES; EraseInitStruct.PageAddress = flash_user_start_addr; EraseInitStruct.NbPages = NbOfPages; if (HAL_FLASHEx_Erase(&EraseInitStruct, &PageError) != HAL_OK) { /* Error occurred while page erase. User can add here some code to deal with this error. PageError will contain the faulty page. */ Error_Handler(); } }
/** * @brief Erases sector. * @param Add: Address of sector to be erased. * @retval 0 if operation is successeful, MAL_FAIL else. */ uint16_t Flash_If_Erase(uint32_t Add) { uint32_t NbOfPages = 0; uint32_t PageError = 0; /* Variable contains Flash operation status */ HAL_StatusTypeDef status; FLASH_EraseInitTypeDef eraseinitstruct; /* Get the number of sector to erase from 1st sector*/ NbOfPages = (USBD_DFU_APP_END_ADD - USBD_DFU_APP_DEFAULT_ADD) / FLASH_PAGE_SIZE; eraseinitstruct.TypeErase = TYPEERASE_PAGES; eraseinitstruct.PageAddress = USBD_DFU_APP_DEFAULT_ADD; eraseinitstruct.NbPages = NbOfPages; status = HAL_FLASHEx_Erase(&eraseinitstruct, &PageError); if (status != HAL_OK) { return 1; } return 0; }
void flash_erase(uint32_t flash_dest, const uint32_t *src, uint32_t num_word32) { // check there is something to write if (num_word32 == 0) { return; } // unlock HAL_FLASH_Unlock(); FLASH_EraseInitTypeDef EraseInitStruct; #if defined(MCU_SERIES_L4) __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_ALL_ERRORS); // erase the sector(s) // The sector returned by flash_get_sector_info can not be used // as the flash has on each bank 0/1 pages 0..255 EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES; EraseInitStruct.Banks = get_bank(flash_dest); EraseInitStruct.Page = get_page(flash_dest); EraseInitStruct.NbPages = get_page(flash_dest + 4 * num_word32 - 1) - EraseInitStruct.Page + 1;; #else // Clear pending flags (if any) __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR); // erase the sector(s) EraseInitStruct.TypeErase = TYPEERASE_SECTORS; EraseInitStruct.VoltageRange = VOLTAGE_RANGE_3; // voltage range needs to be 2.7V to 3.6V EraseInitStruct.Sector = flash_get_sector_info(flash_dest, NULL, NULL); EraseInitStruct.NbSectors = flash_get_sector_info(flash_dest + 4 * num_word32 - 1, NULL, NULL) - EraseInitStruct.Sector + 1; #endif uint32_t SectorError = 0; if (HAL_FLASHEx_Erase(&EraseInitStruct, &SectorError) != HAL_OK) { // error occurred during sector erase HAL_FLASH_Lock(); // lock the flash return; } }
/** * @brief Erases sector. * @param Add: Address of sector to be erased. * @retval 0 if operation is successful, MAL_FAIL else. */ uint16_t Flash_If_Erase(uint32_t Add) { uint32_t startsector = 0, sectorerror = 0; /* Variable contains Flash operation status */ HAL_StatusTypeDef status; FLASH_EraseInitTypeDef eraseinitstruct; /* Get the number of sector */ startsector = GetSector(Add); eraseinitstruct.TypeErase = FLASH_TYPEERASE_SECTORS; eraseinitstruct.Sector = startsector; eraseinitstruct.NbSectors = 1; eraseinitstruct.VoltageRange = FLASH_VOLTAGE_RANGE_3; status = HAL_FLASHEx_Erase(&eraseinitstruct, §orerror); if (status != HAL_OK) { return 1; } return 0; }
void flash_erase(uint32_t sector) { // unlock HAL_FLASH_Unlock(); #if defined(MCU_SERIES_H7) __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_ALL_ERRORS_BANK1 | FLASH_FLAG_ALL_ERRORS_BANK2); #else __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR); #endif // erase the sector(s) FLASH_EraseInitTypeDef EraseInitStruct; EraseInitStruct.TypeErase = TYPEERASE_SECTORS; EraseInitStruct.VoltageRange = VOLTAGE_RANGE_3; // voltage range needs to be 2.7V to 3.6V #if defined(MCU_SERIES_H7) EraseInitStruct.Sector = (sector % 8); if (sector < 8) { EraseInitStruct.Banks = FLASH_BANK_1; } else { EraseInitStruct.Banks = FLASH_BANK_2; } #else EraseInitStruct.Sector = sector; #endif EraseInitStruct.NbSectors = 1; uint32_t SectorError = 0; if (HAL_FLASHEx_Erase(&EraseInitStruct, &SectorError) != HAL_OK) { // error occurred during sector erase HAL_FLASH_Lock(); // lock the flash __fatal_error(); } HAL_FLASH_Lock(); // lock the flash }
int32_t flash_erase_sector(flash_t *obj, uint32_t address) { uint32_t PAGEError = 0; FLASH_EraseInitTypeDef EraseInitStruct; int32_t status = 0; if (!(IS_FLASH_PROGRAM_ADDRESS(address))) { return -1; } if (flash_unlock() != HAL_OK) { return -1; } // Clear Flash status register's flags __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_WRPERR | FLASH_FLAG_PGERR | FLASH_FLAG_OPTVERR); /* MBED HAL erases 1 sector at a time */ /* Fill EraseInit structure*/ EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES; EraseInitStruct.PageAddress = address; EraseInitStruct.NbPages = 1; /* Note: If an erase operation in Flash memory also concerns data in the data or instruction cache, you have to make sure that these data are rewritten before they are accessed during code execution. If this cannot be done safely, it is recommended to flush the caches by setting the DCRST and ICRST bits in the FLASH_CR register. */ if (HAL_FLASHEx_Erase(&EraseInitStruct, &PAGEError) != HAL_OK) { status = -1; } flash_lock(); return status; }
/** * @brief Main program * @param None * @retval None */ int main(void) { /* STM32F0xx HAL library initialization: - Configure the Flash prefetch - Systick timer is configured by default as source of time base, but user can eventually implement his proper time base source (a general purpose timer for example or other time source), keeping in mind that Time base duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and handled in milliseconds basis. - Low Level Initialization */ HAL_Init(); /* Configure the system clock to 48 MHz */ SystemClock_Config(); /* Initialize LED1, LED2 and LED3 */ BSP_LED_Init(LED1); BSP_LED_Init(LED2); BSP_LED_Init(LED3); /* Initialize test status */ MemoryProgramStatus = PASSED; /* Unlock the Flash to enable the flash control register access *************/ HAL_FLASH_Unlock(); /* Unlock the Options Bytes *************************************************/ HAL_FLASH_OB_Unlock(); /* Get pages write protection status ****************************************/ HAL_FLASHEx_OBGetConfig(&OptionsBytesStruct); #ifdef WRITE_PROTECTION_DISABLE /* Check if desired pages are already write protected ***********************/ if((OptionsBytesStruct.WRPPage & FLASH_PAGE_TO_BE_PROTECTED) != FLASH_PAGE_TO_BE_PROTECTED) { /* Restore write protected pages */ OptionsBytesStruct.OptionType = OPTIONBYTE_WRP; OptionsBytesStruct.WRPState = OB_WRPSTATE_DISABLE; OptionsBytesStruct.WRPPage = FLASH_PAGE_TO_BE_PROTECTED; if(HAL_FLASHEx_OBProgram(&OptionsBytesStruct) != HAL_OK) { /* Error occurred while options bytes programming. **********************/ while (1) { BSP_LED_On(LED3); } } /* Generate System Reset to load the new option byte values ***************/ HAL_FLASH_OB_Launch(); } #elif defined WRITE_PROTECTION_ENABLE /* Check if desired pages are not yet write protected ***********************/ if(((~OptionsBytesStruct.WRPPage) & FLASH_PAGE_TO_BE_PROTECTED )!= FLASH_PAGE_TO_BE_PROTECTED) { /* Enable the pages write protection **************************************/ OptionsBytesStruct.OptionType = OPTIONBYTE_WRP; OptionsBytesStruct.WRPState = OB_WRPSTATE_ENABLE; OptionsBytesStruct.WRPPage = FLASH_PAGE_TO_BE_PROTECTED; if(HAL_FLASHEx_OBProgram(&OptionsBytesStruct) != HAL_OK) { /* Error occurred while options bytes programming. **********************/ while (1) { BSP_LED_On(LED3); } } /* Generate System Reset to load the new option byte values ***************/ HAL_FLASH_OB_Launch(); } #endif /* WRITE_PROTECTION_DISABLE */ /* Lock the Options Bytes *************************************************/ HAL_FLASH_OB_Lock(); #ifdef FLASH_PAGE_PROGRAM /* The selected pages are not write protected *******************************/ if ((OptionsBytesStruct.WRPPage & FLASH_PAGE_TO_BE_PROTECTED) != 0x00) { /* Fill EraseInit structure************************************************/ EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES; EraseInitStruct.PageAddress = FLASH_USER_START_ADDR; EraseInitStruct.NbPages = (FLASH_USER_END_ADDR - FLASH_USER_START_ADDR)/FLASH_PAGE_SIZE; if (HAL_FLASHEx_Erase(&EraseInitStruct, &PageError) != HAL_OK) { /* Error occurred while page erase. User can add here some code to deal with this error. PageError will contain the faulty page and then to know the code error on this page, user can call function 'HAL_FLASH_GetError()' */ while (1) { BSP_LED_On(LED3); } } /* FLASH Word program of DATA_32 at addresses defined by FLASH_USER_START_ADDR and FLASH_USER_END_ADDR */ Address = FLASH_USER_START_ADDR; while (Address < FLASH_USER_END_ADDR) { if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, Address, DATA_32) == HAL_OK) { Address = Address + 4; } else { /* Error occurred while writing data in Flash memory. User can add here some code to deal with this error */ while (1) { BSP_LED_On(LED3); } } } /* Check the correctness of written data */ Address = FLASH_USER_START_ADDR; while (Address < FLASH_USER_END_ADDR) { if((*(__IO uint32_t*) Address) != DATA_32) { MemoryProgramStatus = FAILED; } Address += 4; } } else { /* The desired pages are write protected */ /* Check that it is not allowed to write in this page */ Address = FLASH_USER_START_ADDR; if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, Address, DATA_32) != HAL_OK) { /* Error returned during programmation. */ /* Check that WRPERR flag is well set */ if (HAL_FLASH_GetError() == HAL_FLASH_ERROR_WRP) { MemoryProgramStatus = FAILED; } else { /* Another error occurred. User can add here some code to deal with this error */ while (1) { BSP_LED_On(LED3); } } } else { /* Write operation is successful. Should not occur User can add here some code to deal with this error */ while (1) { BSP_LED_On(LED3); } } } #endif /* FLASH_PAGE_PROGRAM */ /* Lock the Flash to disable the flash control register access (recommended to protect the FLASH memory against possible unwanted operation) *********/ HAL_FLASH_Lock(); /*Check if there is an issue to program data*/ if (MemoryProgramStatus == PASSED) { /* No error detected. Switch on LED1*/ BSP_LED_On(LED1); } else { /* Error detected. Switch on LED2*/ BSP_LED_On(LED2); } /* Infinite loop */ while (1) { } }
uint8_t flashProgram(uint32_t addr, uint32_t *data, uint32_t size) /*++ Function Description: This function retriggers a oneshot which allows several of the protocol commands to be receive processed and the Variable Storage to be updated once instead of after each protocol command. In addition, there are two different types of storage: one that is for critical information and is updated maybe only once on the manufacturing floor (SPECIAL). And the other is for standard device variables and state information. Arguments: type - GENERIC_DATA (standard variables) or SPECIAL_DATA (manufacturing variables). Returns: NONE --*/ { FLASH_EraseInitTypeDef EraseInitStruct; uint32_t Address = 0, *Data = 0, PageError = 0, result = 0, length = 0; /* Unlock the Flash to enable the flash control register access *************/ HAL_FLASH_Unlock(); /* Erase the user Flash area (area defined by FLASH_USER_START_ADDR and FLASH_USER_END_ADDR) ***********/ /* Fill EraseInit structure*/ EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES; EraseInitStruct.PageAddress = addr; EraseInitStruct.NbPages = 1;//(FLASH_USER_END_ADDR - addr) / FLASH_PAGE_SIZE; if (HAL_FLASHEx_Erase(&EraseInitStruct, &PageError) != HAL_OK) { /* Error occurred while page erase. User can add here some code to deal with this error. PageError will contain the faulty page and then to know the code error on this page, user can call function 'HAL_FLASH_GetError()' */ /* Infinite loop */ return result; } /* Program the user Flash area word by word (area defined by FLASH_USER_START_ADDR and FLASH_USER_END_ADDR) ***********/ Address = addr; Data = data; // while (Address < FLASH_USER_END_ADDR) while (length < size) { if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, Address, (uint64_t)*Data) == HAL_OK) { Address = Address + 4; Data++; length = length +4; } else { /* Error occurred while writing data in Flash memory. User can add here some code to deal with this error */ return result; } } /* Lock the Flash to disable the flash control register access (recommended to protect the FLASH memory against possible unwanted operation) *********/ HAL_FLASH_Lock(); return result=1; }
/** * @brief Main program * @param None * @retval None */ int main(void) { /* STM32F4xx HAL library initialization: - Configure the Flash prefetch, instruction and Data caches - Systick timer is configured by default as source of time base, but user can eventually implement his proper time base source (a general purpose timer for example or other time source), keeping in mind that Time base duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and handled in milliseconds basis. - Set NVIC Group Priority to 4 - Low Level Initialization: global MSP (MCU Support Package) initialization */ HAL_Init(); /* Configure the system clock to 180 MHz */ SystemClock_Config(); /* Initialize LED1 and LED3 */ BSP_LED_Init(LED1); BSP_LED_Init(LED3); /* Unlock the Flash to enable the flash control register access *************/ HAL_FLASH_Unlock(); /* Erase the user Flash area (area defined by FLASH_USER_START_ADDR and FLASH_USER_END_ADDR) ***********/ /* Get the 1st sector to erase */ FirstSector = GetSector(FLASH_USER_START_ADDR); /* Get the number of sector to erase from 1st sector*/ NbOfSectors = GetSector(FLASH_USER_END_ADDR) - FirstSector + 1; /* Fill EraseInit structure*/ EraseInitStruct.TypeErase = FLASH_TYPEERASE_SECTORS; EraseInitStruct.VoltageRange = FLASH_VOLTAGE_RANGE_3; EraseInitStruct.Sector = FirstSector; EraseInitStruct.NbSectors = NbOfSectors; if (HAL_FLASHEx_Erase(&EraseInitStruct, &SECTORError) != HAL_OK) { /* Error occurred while sector erase. User can add here some code to deal with this error. SECTORError will contain the faulty sector and then to know the code error on this sector, user can call function 'HAL_FLASH_GetError()' */ /* Infinite loop */ while (1) { /* Make LED3 blink (1s period) to indicate error in Erase operation */ BSP_LED_On(LED3); HAL_Delay(1000); BSP_LED_Off(LED3); HAL_Delay(1000); } } /* Note: If an erase operation in Flash memory also concerns data in the data or instruction cache, you have to make sure that these data are rewritten before they are accessed during code execution. If this cannot be done safely, it is recommended to flush the caches by setting the DCRST and ICRST bits in the FLASH_CR register. */ __HAL_FLASH_DATA_CACHE_DISABLE(); __HAL_FLASH_INSTRUCTION_CACHE_DISABLE(); __HAL_FLASH_DATA_CACHE_RESET(); __HAL_FLASH_INSTRUCTION_CACHE_RESET(); __HAL_FLASH_INSTRUCTION_CACHE_ENABLE(); __HAL_FLASH_DATA_CACHE_ENABLE(); /* Program the user Flash area word by word (area defined by FLASH_USER_START_ADDR and FLASH_USER_END_ADDR) ***********/ Address = FLASH_USER_START_ADDR; while (Address < FLASH_USER_END_ADDR) { if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, Address, DATA_32) == HAL_OK) { Address = Address + 4; } else { /* Error occurred while writing data in Flash memory. User can add here some code to deal with this error */ while (1) { /* Make LED3 blink (1s period) to indicate error in Write operation */ BSP_LED_On(LED3); HAL_Delay(1000); BSP_LED_Off(LED3); HAL_Delay(1000); } } } /* Lock the Flash to disable the flash control register access (recommended to protect the FLASH memory against possible unwanted operation) *********/ HAL_FLASH_Lock(); /* Check if the programmed data is OK MemoryProgramStatus = 0: data programmed correctly MemoryProgramStatus != 0: number of words not programmed correctly ******/ Address = FLASH_USER_START_ADDR; MemoryProgramStatus = 0x0; while (Address < FLASH_USER_END_ADDR) { data32 = *(__IO uint32_t *)Address; if (data32 != DATA_32) { MemoryProgramStatus++; } Address = Address + 4; } /*Check if there is an issue to program data*/ if (MemoryProgramStatus == 0) { /* No error detected. Switch on LED1*/ BSP_LED_On(LED1); } else { /* Error detected. Switch on LED3*/ BSP_LED_On(LED3); } /* Infinite loop */ while (1) { } }
int main(void) { HAL_StatusTypeDef status; FLASH_EraseInitTypeDef eraseInit; uint32_t sectorError; uint32_t *ptr=ADDRESS_SECTOR_18; uint32_t checkCR; int guard=0; while(1){ status=HAL_FLASH_Unlock(); //this guard function is to program the Flash if(guard){ while(status==HAL_BUSY); status=HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, ADDRESS_SECTOR_18, DATA_PROGRAM); while(status==HAL_BUSY); guard=0; } //this guard function is to sector erase the Flash if(guard){ flashEraseInit(&eraseInit, FLASH_TYPEERASE_SECTORS, 0, FLASH_SECTOR_18, 1, FLASH_VOLTAGE_RANGE_3); while(status==HAL_BUSY); HAL_FLASHEx_Erase(&eraseInit,§orError); while(status==HAL_BUSY); guard=0; } //this guard function is to Mass erase the Flash if(guard){ flashEraseInit(&eraseInit, FLASH_TYPEERASE_MASSERASE, 0, 0, 1, FLASH_VOLTAGE_RANGE_3); while(status==HAL_BUSY); HAL_FLASHEx_Erase(&eraseInit,§orError); while(status==HAL_BUSY); guard=0; } status=HAL_FLASH_Lock(); } }
// FIXME: HAL for now this will only work for F4/F7 as flash layout is different void writeEEPROM(void) { // Generate compile time error if the config does not fit in the reserved area of flash. BUILD_BUG_ON(sizeof(master_t) > FLASH_TO_RESERVE_FOR_CONFIG); HAL_StatusTypeDef status; uint32_t wordOffset; int8_t attemptsRemaining = 3; suspendRxSignal(); // prepare checksum/version constants masterConfig.version = EEPROM_CONF_VERSION; masterConfig.size = sizeof(master_t); masterConfig.magic_be = 0xBE; masterConfig.magic_ef = 0xEF; masterConfig.chk = 0; // erase checksum before recalculating masterConfig.chk = calculateChecksum((const uint8_t *) &masterConfig, sizeof(master_t)); // write it /* Unlock the Flash to enable the flash control register access *************/ HAL_FLASH_Unlock(); while (attemptsRemaining--) { /* Fill EraseInit structure*/ FLASH_EraseInitTypeDef EraseInitStruct = {0}; EraseInitStruct.TypeErase = FLASH_TYPEERASE_SECTORS; EraseInitStruct.VoltageRange = FLASH_VOLTAGE_RANGE_3; // 2.7-3.6V EraseInitStruct.Sector = (FLASH_SECTOR_TOTAL-1); EraseInitStruct.NbSectors = 1; uint32_t SECTORError; status = HAL_FLASHEx_Erase(&EraseInitStruct, &SECTORError); if (status != HAL_OK) { continue; } else { for (wordOffset = 0; wordOffset < sizeof(master_t); wordOffset += 4) { status = HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, CONFIG_START_FLASH_ADDRESS + wordOffset, *(uint32_t *) ((char *) &masterConfig + wordOffset)); if(status != HAL_OK) { break; } } } if (status == HAL_OK) { break; } } HAL_FLASH_Lock(); // Flash write failed - just die now if (status != HAL_OK || !isEEPROMContentValid()) { failureMode(FAILURE_FLASH_WRITE_FAILED); } resumeRxSignal(); }
/** * @brief Erases PAGE and PAGE1 and writes VALID_PAGE header to PAGE * @param None * @retval Status of the last operation (Flash write or erase) done during * EEPROM formating */ static HAL_StatusTypeDef EE_Format(void) { HAL_StatusTypeDef FlashStatus = HAL_OK; uint32_t SectorError = 0; FLASH_EraseInitTypeDef pEraseInit; pEraseInit.TypeErase = FLASH_TYPEERASE_SECTORS; pEraseInit.Sector = PAGE0_ID; pEraseInit.NbSectors = 1; pEraseInit.VoltageRange = VOLTAGE_RANGE; /* Erase Page0 */ if(!EE_VerifyPageFullyErased(PAGE0_BASE_ADDRESS)) { FlashStatus = HAL_FLASHEx_Erase(&pEraseInit, &SectorError); /* If erase operation was failed, a Flash error code is returned */ if (FlashStatus != HAL_OK) { return FlashStatus; } } /* Set Page0 as valid page: Write VALID_PAGE at Page0 base address */ FlashStatus = HAL_FLASH_Program(TYPEPROGRAM_HALFWORD, PAGE0_BASE_ADDRESS, VALID_PAGE); /* If program operation was failed, a Flash error code is returned */ if (FlashStatus != HAL_OK) { return FlashStatus; } pEraseInit.Sector = PAGE1_ID; /* Erase Page1 */ if(!EE_VerifyPageFullyErased(PAGE1_BASE_ADDRESS)) { FlashStatus = HAL_FLASHEx_Erase(&pEraseInit, &SectorError); /* If erase operation was failed, a Flash error code is returned */ if (FlashStatus != HAL_OK) { return FlashStatus; } } return HAL_OK; }
/** * @brief Erases PAGE and PAGE1 and writes VALID_PAGE header to PAGE * @param None * @retval Status of the last operation (Flash write or erase) done during * EEPROM formating */ static HAL_StatusTypeDef EE_Format(void) { HAL_StatusTypeDef flashstatus = HAL_OK; uint32_t page_error = 0; FLASH_EraseInitTypeDef s_eraseinit; s_eraseinit.TypeErase = FLASH_TYPEERASE_PAGES; s_eraseinit.PageAddress = PAGE0_ID; s_eraseinit.NbPages = 1; /* Erase Page0 */ if(!EE_VerifyPageFullyErased(PAGE0_BASE_ADDRESS)) { flashstatus = HAL_FLASHEx_Erase(&s_eraseinit, &page_error); /* If erase operation was failed, a Flash error code is returned */ if (flashstatus != HAL_OK) { return flashstatus; } } /* Set Page0 as valid page: Write VALID_PAGE at Page0 base address */ flashstatus = HAL_FLASH_Program(FLASH_TYPEPROGRAM_HALFWORD, PAGE0_BASE_ADDRESS, VALID_PAGE); /* If program operation was failed, a Flash error code is returned */ if (flashstatus != HAL_OK) { return flashstatus; } s_eraseinit.PageAddress = PAGE1_ID; /* Erase Page1 */ if(!EE_VerifyPageFullyErased(PAGE1_BASE_ADDRESS)) { flashstatus = HAL_FLASHEx_Erase(&s_eraseinit, &page_error); /* If erase operation was failed, a Flash error code is returned */ if (flashstatus != HAL_OK) { return flashstatus; } } return HAL_OK; }
void EE_WriteVariable(EepromAddress32 virtAddress, uint32_t data) { uint16_t length=EE_LastUnusedVariable; uint32_t address = FLASH_USER_START_ADDR; for (uint16_t varIndex = 0;varIndex < length;varIndex++) { uint32_t data32 = *(__IO uint32_t *)address; EE_storage[varIndex] = data32; address = address + 4; } EE_storage[virtAddress] = data; //write the new data HAL_FLASH_Unlock(); /* Get the 1st page to erase */ uint32_t FirstPage = GetPage(FLASH_USER_START_ADDR); /* Get the number of pages to erase from 1st page */ uint32_t NbOfPages = GetPage(FLASH_USER_END_ADDR) - FirstPage + 1; /* Get the bank */ uint32_t BankNumber = GetBank(FLASH_USER_START_ADDR); uint32_t PAGEError; /* Fill EraseInit structure*/ FLASH_EraseInitTypeDef EraseInitStruct; EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES; EraseInitStruct.Banks = BankNumber; EraseInitStruct.Page = FirstPage; EraseInitStruct.NbPages = NbOfPages; HAL_Error_Handler(HAL_FLASHEx_Erase(&EraseInitStruct, &PAGEError)); address = FLASH_USER_START_ADDR; for (uint16_t varIndex = 0;varIndex < length;varIndex+=2) { uint64_t toWrite=EE_storage[varIndex]; if (varIndex+1<length) { toWrite|= ((uint64_t)EE_storage[varIndex+1])<<32; } HAL_Error_Handler(HAL_FLASH_Program(FLASH_TYPEPROGRAM_DOUBLEWORD, address, toWrite)); address = address + 8; } HAL_FLASH_Lock(); }
uint8_t setNetworkUpgradeTarg(uint8_t targ) { uint32_t i; /*Unlock the Flash to enable the flash control register access*/ HAL_FLASH_Unlock(); /* Fill EraseInit structure ,Here just SECTOR_11 need to be erased*/ EraseInitStruct.TypeErase = TYPEERASE_SECTORS; EraseInitStruct.VoltageRange = VOLTAGE_RANGE_3; EraseInitStruct.Sector = FLASH_SECTOR_2; EraseInitStruct.NbSectors = 1; if (HAL_FLASHEx_Erase(&EraseInitStruct, &SectorError) != HAL_OK) { /*Erase failed*/ printf("Set network Upgrade error\n\r"); return 0; } /*Program the selected FLASH area byte by byte*/ Address = FLASH_TARG_START_ADDR; if (HAL_FLASH_Program(TYPEPROGRAM_BYTE, Address,targ) != HAL_OK) { printf("Set network Upgrade error\n\r"); return 0; } /*Lock the flash to ensure the security of my program*/ HAL_FLASH_Lock(); Address = FLASH_TARG_START_ADDR; MemoryProgramStatus = 0; data8 = *(__IO uint8_t*)Address; if ( data8 != targ ) { MemoryProgramStatus++; } /*Check if there is an issue to program data*/ if (MemoryProgramStatus != 0) { printf("Set network Upgrade error\n\r"); return 0; } return 1; }