2 ******************************************************************************
3 * @file stm32f4xx_hal_flash.c
4 * @author MCD Application Team
7 * @brief FLASH HAL module driver.
8 * This file provides firmware functions to manage the following
9 * functionalities of the internal FLASH memory:
10 * + Program operations functions
11 * + Memory Control functions
12 * + Peripheral Errors functions
15 ==============================================================================
16 ##### FLASH peripheral features #####
17 ==============================================================================
19 [..] The Flash memory interface manages CPU AHB I-Code and D-Code accesses
20 to the Flash memory. It implements the erase and program Flash memory operations
21 and the read and write protection mechanisms.
23 [..] The Flash memory interface accelerates code execution with a system of instruction
24 prefetch and cache lines.
26 [..] The FLASH main features are:
27 (+) Flash memory read operations
28 (+) Flash memory program/erase operations
29 (+) Read / write protections
30 (+) Prefetch on I-Code
31 (+) 64 cache lines of 128 bits on I-Code
32 (+) 8 cache lines of 128 bits on D-Code
35 ##### How to use this driver #####
36 ==============================================================================
38 This driver provides functions and macros to configure and program the FLASH
39 memory of all STM32F4xx devices.
41 (#) FLASH Memory IO Programming functions:
42 (++) Lock and Unlock the FLASH interface using HAL_FLASH_Unlock() and
43 HAL_FLASH_Lock() functions
44 (++) Program functions: byte, half word, word and double word
45 (++) There Two modes of programming :
46 (+++) Polling mode using HAL_FLASH_Program() function
47 (+++) Interrupt mode using HAL_FLASH_Program_IT() function
49 (#) Interrupts and flags management functions :
50 (++) Handle FLASH interrupts by calling HAL_FLASH_IRQHandler()
51 (++) Wait for last FLASH operation according to its status
52 (++) Get error flag status by calling HAL_SetErrorCode()
55 In addition to these functions, this driver includes a set of macros allowing
56 to handle the following operations:
58 (+) Enable/Disable the prefetch buffer
59 (+) Enable/Disable the Instruction cache and the Data cache
60 (+) Reset the Instruction cache and the Data cache
61 (+) Enable/Disable the FLASH interrupts
62 (+) Monitor the FLASH flags status
65 ******************************************************************************
68 * <h2><center>© COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
70 * Redistribution and use in source and binary forms, with or without modification,
71 * are permitted provided that the following conditions are met:
72 * 1. Redistributions of source code must retain the above copyright notice,
73 * this list of conditions and the following disclaimer.
74 * 2. Redistributions in binary form must reproduce the above copyright notice,
75 * this list of conditions and the following disclaimer in the documentation
76 * and/or other materials provided with the distribution.
77 * 3. Neither the name of STMicroelectronics nor the names of its contributors
78 * may be used to endorse or promote products derived from this software
79 * without specific prior written permission.
81 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
82 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
83 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
84 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
85 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
86 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
87 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
88 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
89 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
90 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
92 ******************************************************************************
95 /* Includes ------------------------------------------------------------------*/
96 #include "stm32f4xx_hal.h"
98 /** @addtogroup STM32F4xx_HAL_Driver
103 * @brief FLASH HAL module driver
107 #ifdef HAL_FLASH_MODULE_ENABLED
109 /* Private typedef -----------------------------------------------------------*/
110 /* Private define ------------------------------------------------------------*/
111 #define SECTOR_MASK ((uint32_t)0xFFFFFF07)
113 #define HAL_FLASH_TIMEOUT_VALUE ((uint32_t)50000)/* 50 s */
114 /* Private macro -------------------------------------------------------------*/
115 /* Private variables ---------------------------------------------------------*/
116 /* Variable used for Erase sectors under interruption */
117 FLASH_ProcessTypeDef pFlash;
120 /* Private function prototypes -----------------------------------------------*/
121 /* Program operations */
122 static void FLASH_Program_DoubleWord(uint32_t Address, uint64_t Data);
123 static void FLASH_Program_Word(uint32_t Address, uint32_t Data);
124 static void FLASH_Program_HalfWord(uint32_t Address, uint16_t Data);
125 static void FLASH_Program_Byte(uint32_t Address, uint8_t Data);
126 static void FLASH_SetErrorCode(void);
128 HAL_StatusTypeDef FLASH_WaitForLastOperation(uint32_t Timeout);
130 /* Private functions ---------------------------------------------------------*/
131 /** @defgroup FLASH_Private_Functions FLASH Private functions
135 /** @defgroup FLASH_Group1 Programming operation functions
136 * @brief Programming operation functions
139 ===============================================================================
140 ##### Programming operation functions #####
141 ===============================================================================
143 This subsection provides a set of functions allowing to manage the FLASH
151 * @brief Program byte, halfword, word or double word at a specified address
152 * @param TypeProgram: Indicate the way to program at a specified address.
153 * This parameter can be a value of @ref FLASH_Type_Program
154 * @param Address: specifies the address to be programmed.
155 * @param Data: specifies the data to be programmed
157 * @retval HAL_StatusTypeDef HAL Status
159 HAL_StatusTypeDef HAL_FLASH_Program(uint32_t TypeProgram, uint32_t Address, uint64_t Data)
161 HAL_StatusTypeDef status = HAL_ERROR;
166 /* Check the parameters */
167 assert_param(IS_TYPEPROGRAM(TypeProgram));
169 /* Wait for last operation to be completed */
170 status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE);
174 if(TypeProgram == TYPEPROGRAM_BYTE)
176 /*Program byte (8-bit) at a specified address.*/
177 FLASH_Program_Byte(Address, (uint8_t) Data);
179 else if(TypeProgram == TYPEPROGRAM_HALFWORD)
181 /*Program halfword (16-bit) at a specified address.*/
182 FLASH_Program_HalfWord(Address, (uint16_t) Data);
184 else if(TypeProgram == TYPEPROGRAM_WORD)
186 /*Program word (32-bit) at a specified address.*/
187 FLASH_Program_Word(Address, (uint32_t) Data);
191 /*Program double word (64-bit) at a specified address.*/
192 FLASH_Program_DoubleWord(Address, Data);
195 /* Wait for last operation to be completed */
196 status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE);
198 /* If the program operation is completed, disable the PG Bit */
199 FLASH->CR &= (~FLASH_CR_PG);
202 /* Process Unlocked */
203 __HAL_UNLOCK(&pFlash);
209 * @brief Program byte, halfword, word or double word at a specified address with interrupt enabled.
210 * @param TypeProgram: Indicate the way to program at a specified address.
211 * This parameter can be a value of @ref FLASH_Type_Program
212 * @param Address: specifies the address to be programmed.
213 * @param Data: specifies the data to be programmed
217 HAL_StatusTypeDef HAL_FLASH_Program_IT(uint32_t TypeProgram, uint32_t Address, uint64_t Data)
219 HAL_StatusTypeDef status = HAL_OK;
224 /* Check the parameters */
225 assert_param(IS_TYPEPROGRAM(TypeProgram));
227 /* Enable End of FLASH Operation interrupt */
228 __HAL_FLASH_ENABLE_IT(FLASH_IT_EOP);
230 /* Enable Error source interrupt */
231 __HAL_FLASH_ENABLE_IT(FLASH_IT_ERR);
233 /* Clear pending flags (if any) */
234 __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR |\
235 FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR| FLASH_FLAG_PGSERR);
237 pFlash.ProcedureOnGoing = FLASH_PROC_PROGRAM;
238 pFlash.Address = Address;
240 if(TypeProgram == TYPEPROGRAM_BYTE)
242 /*Program byte (8-bit) at a specified address.*/
243 FLASH_Program_Byte(Address, (uint8_t) Data);
245 else if(TypeProgram == TYPEPROGRAM_HALFWORD)
247 /*Program halfword (16-bit) at a specified address.*/
248 FLASH_Program_HalfWord(Address, (uint16_t) Data);
250 else if(TypeProgram == TYPEPROGRAM_WORD)
252 /*Program word (32-bit) at a specified address.*/
253 FLASH_Program_Word(Address, (uint32_t) Data);
257 /*Program double word (64-bit) at a specified address.*/
258 FLASH_Program_DoubleWord(Address, Data);
265 * @brief This function handles FLASH interrupt request.
269 void HAL_FLASH_IRQHandler(void)
273 /* If the program operation is completed, disable the PG Bit */
274 FLASH->CR &= (~FLASH_CR_PG);
276 /* If the erase operation is completed, disable the SER Bit */
277 FLASH->CR &= (~FLASH_CR_SER);
278 FLASH->CR &= SECTOR_MASK;
280 /* if the erase operation is completed, disable the MER Bit */
281 FLASH->CR &= (~FLASH_MER_BIT);
283 /* Check FLASH End of Operation flag */
284 if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_EOP) != RESET)
286 if(pFlash.ProcedureOnGoing == FLASH_PROC_SECTERASE)
288 /*Nb of sector to erased can be decreased*/
289 pFlash.NbSectorsToErase--;
291 /* Check if there are still sectors to erase*/
292 if(pFlash.NbSectorsToErase != 0)
294 temp = pFlash.Sector;
295 /*Indicate user which sector has been erased*/
296 HAL_FLASH_EndOfOperationCallback(temp);
298 /* Clear pending flags (if any) */
299 __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR |\
300 FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR| FLASH_FLAG_PGSERR);
302 /*Increment sector number*/
303 temp = ++pFlash.Sector;
304 FLASH_Erase_Sector(temp, pFlash.VoltageForErase);
308 /*No more sectors to Erase, user callback can be called.*/
309 /*Reset Sector and stop Erase sectors procedure*/
310 pFlash.Sector = temp = 0xFFFFFFFF;
311 pFlash.ProcedureOnGoing = FLASH_PROC_NONE;
312 /* FLASH EOP interrupt user callback */
313 HAL_FLASH_EndOfOperationCallback(temp);
314 /* Clear FLASH End of Operation pending bit */
315 __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP);
320 if (pFlash.ProcedureOnGoing == FLASH_PROC_MASSERASE)
322 /*MassErase ended. Return the selected bank*/
323 /* FLASH EOP interrupt user callback */
324 HAL_FLASH_EndOfOperationCallback(pFlash.Bank);
328 /*Program ended. Return the selected address*/
329 /* FLASH EOP interrupt user callback */
330 HAL_FLASH_EndOfOperationCallback(pFlash.Address);
332 pFlash.ProcedureOnGoing = FLASH_PROC_NONE;
333 /* Clear FLASH End of Operation pending bit */
334 __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP);
339 /* Check FLASH operation error flags */
340 if(__HAL_FLASH_GET_FLAG((FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | \
341 FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR | FLASH_FLAG_RDERR)) != RESET)
343 if(pFlash.ProcedureOnGoing == FLASH_PROC_SECTERASE)
345 /*return the faulty sector*/
346 temp = pFlash.Sector;
347 pFlash.Sector = 0xFFFFFFFF;
349 else if (pFlash.ProcedureOnGoing == FLASH_PROC_MASSERASE)
351 /*return the faulty bank*/
356 /*retrun the faulty address*/
357 temp = pFlash.Address;
360 /*Save the Error code*/
361 FLASH_SetErrorCode();
363 /* FLASH error interrupt user callback */
364 HAL_FLASH_OperationErrorCallback(temp);
365 /* Clear FLASH error pending bits */
366 __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR |\
367 FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR | FLASH_FLAG_RDERR);
369 /*Stop the procedure ongoing*/
370 pFlash.ProcedureOnGoing = FLASH_PROC_NONE;
373 if(pFlash.ProcedureOnGoing == FLASH_PROC_NONE)
375 /* Disable End of FLASH Operation interrupt */
376 __HAL_FLASH_DISABLE_IT(FLASH_IT_EOP);
378 /* Disable Error source interrupt */
379 __HAL_FLASH_DISABLE_IT(FLASH_IT_ERR);
381 /* Process Unlocked */
382 __HAL_UNLOCK(&pFlash);
388 * @brief FLASH end of operation interrupt callback
389 * @param ReturnValue: The value saved in this parameter depends on the ongoing procedure
390 * Mass Erase: Bank number which has been requested to erase
391 * Sectors Erase: Sector which has been erased
392 * (if 0xFFFFFFFF, it means that all the selected sectors have been erased)
393 * Program: Address which was selected for data program
396 __weak void HAL_FLASH_EndOfOperationCallback(uint32_t ReturnValue)
398 /* NOTE : This function Should not be modified, when the callback is needed,
399 the HAL_FLASH_EndOfOperationCallback could be implemented in the user file
404 * @brief FLASH operation error interrupt callback
405 * @param ReturnValue: The value saved in this parameter depends on the ongoing procedure
406 * Mass Erase: Bank number which has been requested to erase
407 * Sectors Erase: Sector number which returned an error
408 * Program: Address which was selected for data program
411 __weak void HAL_FLASH_OperationErrorCallback(uint32_t ReturnValue)
413 /* NOTE : This function Should not be modified, when the callback is needed,
414 the HAL_FLASH_OperationErrorCallback could be implemented in the user file
422 /** @defgroup FLASH_Group2 Peripheral Control functions
423 * @brief management functions
426 ===============================================================================
427 ##### Peripheral Control functions #####
428 ===============================================================================
430 This subsection provides a set of functions allowing to control the FLASH
438 * @brief Unlock the FLASH control register access
442 HAL_StatusTypeDef HAL_FLASH_Unlock(void)
444 if((FLASH->CR & FLASH_CR_LOCK) != RESET)
446 /* Authorize the FLASH Registers access */
447 FLASH->KEYR = FLASH_KEY1;
448 FLASH->KEYR = FLASH_KEY2;
459 * @brief Locks the FLASH control register access
463 HAL_StatusTypeDef HAL_FLASH_Lock(void)
465 /* Set the LOCK Bit to lock the FLASH Registers access */
466 FLASH->CR |= FLASH_CR_LOCK;
473 * @brief Unlock the FLASH Option Control Registers access.
477 HAL_StatusTypeDef HAL_FLASH_OB_Unlock(void)
479 if((FLASH->OPTCR & FLASH_OPTCR_OPTLOCK) != RESET)
481 /* Authorizes the Option Byte register programming */
482 FLASH->OPTKEYR = FLASH_OPT_KEY1;
483 FLASH->OPTKEYR = FLASH_OPT_KEY2;
494 * @brief Lock the FLASH Option Control Registers access.
498 HAL_StatusTypeDef HAL_FLASH_OB_Lock(void)
500 /* Set the OPTLOCK Bit to lock the FLASH Option Byte Registers access */
501 FLASH->OPTCR |= FLASH_OPTCR_OPTLOCK;
507 * @brief Launch the option byte loading.
511 HAL_StatusTypeDef HAL_FLASH_OB_Launch(void)
513 /* Set the OPTSTRT bit in OPTCR register */
514 *(__IO uint8_t *)OPTCR_BYTE0_ADDRESS |= FLASH_OPTCR_OPTSTRT;
516 /* Wait for last operation to be completed */
517 return(FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE));
524 /** @defgroup FLASH_Group3 Peripheral State and Errors functions
525 * @brief Peripheral Errors functions
528 ===============================================================================
529 ##### Peripheral Errors functions #####
530 ===============================================================================
532 This subsection permits to get in run-time Errors of the FLASH peripheral.
539 * @brief Get the specific FLASH error flag.
541 * @retval FLASH_ErrorCode: The returned value can be:
542 * @arg FLASH_ERROR_RD: FLASH Read Protection error flag (PCROP)
543 * @arg FLASH_ERROR_PGS: FLASH Programming Sequence error flag
544 * @arg FLASH_ERROR_PGP: FLASH Programming Parallelism error flag
545 * @arg FLASH_ERROR_PGA: FLASH Programming Alignment error flag
546 * @arg FLASH_ERROR_WRP: FLASH Write protected error flag
547 * @arg FLASH_ERROR_OPERATION: FLASH operation Error flag
549 FLASH_ErrorTypeDef HAL_FLASH_GetError(void)
551 return pFlash.ErrorCode;
559 * @brief Wait for a FLASH operation to complete.
560 * @param Timeout: maximum flash operationtimeout
563 HAL_StatusTypeDef FLASH_WaitForLastOperation(uint32_t Timeout)
565 uint32_t tickstart = 0;
566 /* Wait for the FLASH operation to complete by polling on BUSY flag to be reset.
567 Even if the FLASH operation fails, the BUSY flag will be reset and an error
570 tickstart = HAL_GetTick();
572 while(__HAL_FLASH_GET_FLAG(FLASH_FLAG_BSY) != RESET)
574 if(Timeout != HAL_MAX_DELAY)
576 if((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout))
583 if(__HAL_FLASH_GET_FLAG((FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | \
584 FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR | FLASH_FLAG_RDERR)) != RESET)
586 /*Save the error code*/
587 FLASH_SetErrorCode();
591 /* If there is an error flag set */
597 * @brief Program a double word (64-bit) at a specified address.
598 * @note This function must be used when the device voltage range is from
599 * 2.7V to 3.6V and an External Vpp is present.
601 * @note If an erase and a program operations are requested simultaneously,
602 * the erase operation is performed before the program one.
604 * @param Address: specifies the address to be programmed.
605 * @param Data: specifies the data to be programmed.
608 static void FLASH_Program_DoubleWord(uint32_t Address, uint64_t Data)
610 /* Check the parameters */
611 assert_param(IS_FLASH_ADDRESS(Address));
613 /* If the previous operation is completed, proceed to program the new data */
614 FLASH->CR &= CR_PSIZE_MASK;
615 FLASH->CR |= FLASH_PSIZE_DOUBLE_WORD;
616 FLASH->CR |= FLASH_CR_PG;
618 *(__IO uint64_t*)Address = Data;
623 * @brief Program word (32-bit) at a specified address.
624 * @note This function must be used when the device voltage range is from
627 * @note If an erase and a program operations are requested simultaneously,
628 * the erase operation is performed before the program one.
630 * @param Address: specifies the address to be programmed.
631 * @param Data: specifies the data to be programmed.
634 static void FLASH_Program_Word(uint32_t Address, uint32_t Data)
636 /* Check the parameters */
637 assert_param(IS_FLASH_ADDRESS(Address));
639 /* If the previous operation is completed, proceed to program the new data */
640 FLASH->CR &= CR_PSIZE_MASK;
641 FLASH->CR |= FLASH_PSIZE_WORD;
642 FLASH->CR |= FLASH_CR_PG;
644 *(__IO uint32_t*)Address = Data;
648 * @brief Program a half-word (16-bit) at a specified address.
649 * @note This function must be used when the device voltage range is from
652 * @note If an erase and a program operations are requested simultaneously,
653 * the erase operation is performed before the program one.
655 * @param Address: specifies the address to be programmed.
656 * @param Data: specifies the data to be programmed.
659 static void FLASH_Program_HalfWord(uint32_t Address, uint16_t Data)
661 /* Check the parameters */
662 assert_param(IS_FLASH_ADDRESS(Address));
664 /* If the previous operation is completed, proceed to program the new data */
665 FLASH->CR &= CR_PSIZE_MASK;
666 FLASH->CR |= FLASH_PSIZE_HALF_WORD;
667 FLASH->CR |= FLASH_CR_PG;
669 *(__IO uint16_t*)Address = Data;
673 * @brief Program byte (8-bit) at a specified address.
674 * @note This function must be used when the device voltage range is from
677 * @note If an erase and a program operations are requested simultaneously,
678 * the erase operation is performed before the program one.
680 * @param Address: specifies the address to be programmed.
681 * @param Data: specifies the data to be programmed.
684 static void FLASH_Program_Byte(uint32_t Address, uint8_t Data)
686 /* Check the parameters */
687 assert_param(IS_FLASH_ADDRESS(Address));
689 /* If the previous operation is completed, proceed to program the new data */
690 FLASH->CR &= CR_PSIZE_MASK;
691 FLASH->CR |= FLASH_PSIZE_BYTE;
692 FLASH->CR |= FLASH_CR_PG;
694 *(__IO uint8_t*)Address = Data;
698 * @brief Set the specific FLASH error flag.
702 static void FLASH_SetErrorCode(void)
704 if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_WRPERR) != RESET)
706 pFlash.ErrorCode = FLASH_ERROR_WRP;
709 if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_PGAERR) != RESET)
711 pFlash.ErrorCode |= (FLASH_ErrorTypeDef)FLASH_ERROR_PGA;
714 if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_PGPERR) != RESET)
716 pFlash.ErrorCode |= FLASH_ERROR_PGP;
719 if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_PGSERR) != RESET)
721 pFlash.ErrorCode |= FLASH_ERROR_PGS;
724 if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_RDERR) != RESET)
726 pFlash.ErrorCode |= FLASH_ERROR_RD;
729 if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_OPERR) != RESET)
731 pFlash.ErrorCode |= FLASH_ERROR_OPERATION;
739 #endif /* HAL_FLASH_MODULE_ENABLED */
749 /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/