2 ******************************************************************************
3 * @file stm32f0xx_hal_flash.c
4 * @author MCD Application Team
6 * @date 11-December-2014
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 State functions
15 ==============================================================================
16 ##### FLASH peripheral features #####
17 ==============================================================================
18 [..] The Flash memory interface manages CPU AHB I-Code and D-Code accesses
19 to the Flash memory. It implements the erase and program Flash memory operations
20 and the read and write protection mechanisms.
22 [..] The Flash memory interface accelerates code execution with a system of instruction
25 [..] The FLASH main features are:
26 (+) Flash memory read operations
27 (+) Flash memory program/erase operations
28 (+) Read / write protections
29 (+) Prefetch on I-Code
30 (+) Option Bytes programming
32 ##### How to use this driver #####
33 ==============================================================================
35 This driver provides functions and macros to configure and program the FLASH
36 memory of all STM32F0xx devices. These functions are split in 3 groups:
38 (#) FLASH Memory I/O Programming functions: this group includes all needed
39 functions to erase and program the main memory:
40 (++) Lock and Unlock the FLASH interface
41 (++) Erase function: Erase page, erase all pages
42 (++) Program functions: half word, word and doubleword
44 (#) Option Bytes Programming functions: this group includes all needed
45 functions to manage the Option Bytes:
46 (++) Lock and Unlock the Option Bytes
47 (++) Erase Option Bytes
48 (++) Set/Reset the write protection
49 (++) Set the Read protection Level
50 (++) Program the user Option Bytes
51 (++) Program the data Option Bytes
52 (++) Launch the Option Bytes loader
54 (#) Interrupts and flags management functions : this group
55 includes all needed functions to:
56 (++) Handle FLASH interrupts
57 (++) Wait for last FLASH operation according to its status
58 (++) Get error flag status
60 [..] In addition to these function, this driver includes a set of macros allowing
61 to handle the following operations:
64 (+) Enable/Disable the prefetch buffer
65 (+) Enable/Disable the FLASH interrupts
66 (+) Monitor the FLASH flags status
69 ******************************************************************************
72 * <h2><center>© COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
74 * Redistribution and use in source and binary forms, with or without modification,
75 * are permitted provided that the following conditions are met:
76 * 1. Redistributions of source code must retain the above copyright notice,
77 * this list of conditions and the following disclaimer.
78 * 2. Redistributions in binary form must reproduce the above copyright notice,
79 * this list of conditions and the following disclaimer in the documentation
80 * and/or other materials provided with the distribution.
81 * 3. Neither the name of STMicroelectronics nor the names of its contributors
82 * may be used to endorse or promote products derived from this software
83 * without specific prior written permission.
85 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
86 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
87 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
88 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
89 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
90 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
91 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
92 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
93 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
94 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
96 ******************************************************************************
99 /* Includes ------------------------------------------------------------------*/
100 #include "stm32f0xx_hal.h"
102 /** @addtogroup STM32F0xx_HAL_Driver
106 /** @defgroup FLASH FLASH HAL module driver
107 * @brief FLASH HAL module driver
111 #ifdef HAL_FLASH_MODULE_ENABLED
113 /* Private typedef -----------------------------------------------------------*/
114 /* Private define ------------------------------------------------------------*/
115 /** @defgroup FLASH_Private_Defines FLASH Private Define
122 /* Private macro -------------------------------------------------------------*/
123 /** @defgroup FLASH_Private_Macros FLASH Private Macros
131 /* Private variables ---------------------------------------------------------*/
132 /** @defgroup FLASH_Private_Variables FLASH Private Variables
135 /* Variables used for Erase pages under interruption*/
136 FLASH_ProcessTypeDef pFlash
;
141 /* Private function prototypes -----------------------------------------------*/
142 /** @defgroup FLASH_Private_Functions FLASH Private Functions
145 /* Erase operations */
146 void FLASH_PageErase(uint32_t PageAddress
);
148 /* Program operations */
149 static void FLASH_Program_HalfWord(uint32_t Address
, uint16_t Data
);
151 HAL_StatusTypeDef
FLASH_WaitForLastOperation(uint32_t Timeout
);
152 static void FLASH_SetErrorCode(void);
158 /* Exported functions ---------------------------------------------------------*/
159 /** @defgroup FLASH_Exported_Functions FLASH Exported Functions
163 /** @defgroup FLASH_Exported_Functions_Group1 I/O operation functions
164 * @brief Data transfers functions
167 ===============================================================================
168 ##### IO operation functions #####
169 ===============================================================================
171 This subsection provides a set of functions allowing to manage the FLASH
172 program operations (write/erase).
179 * @brief Program halfword, word or double word at a specified address
180 * @note The function HAL_FLASH_Unlock() should be called before to unlock the FLASH interface
181 * The function HAL_FLASH_Lock() should be called after to lock the FLASH interface
183 * @note If an erase and a program operations are requested simultaneously,
184 * the erase operation is performed before the program one.
186 * @note FLASH should be previously erased before new programmation (only exception to this
187 * is when 0x0000 is programmed)
189 * @param TypeProgram: Indicate the way to program at a specified address.
190 * This parameter can be a value of @ref FLASH_Type_Program
191 * @param Address: Specifies the address to be programmed.
192 * @param Data: Specifies the data to be programmed
194 * @retval HAL_StatusTypeDef HAL Status
196 HAL_StatusTypeDef
HAL_FLASH_Program(uint32_t TypeProgram
, uint32_t Address
, uint64_t Data
)
198 HAL_StatusTypeDef status
= HAL_ERROR
;
200 uint8_t nbiterations
= 0;
205 /* Check the parameters */
206 assert_param(IS_TYPEPROGRAM(TypeProgram
));
207 assert_param(IS_FLASH_PROGRAM_ADDRESS(Address
));
209 /* Wait for last operation to be completed */
210 status
= FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE
);
214 if(TypeProgram
== TYPEPROGRAM_HALFWORD
)
216 /* Program halfword (16-bit) at a specified address. */
219 else if(TypeProgram
== TYPEPROGRAM_WORD
)
221 /* Program word (32-bit = 2*16-bit) at a specified address. */
226 /* Program double word (64-bit = 4*16-bit) at a specified address. */
230 for (index
= 0; index
< nbiterations
; index
++)
232 FLASH_Program_HalfWord((Address
+ (2*index
)), (uint16_t)(Data
>> (16*index
)));
234 /* Wait for last operation to be completed */
235 status
= FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE
);
237 /* If the program operation is completed, disable the PG Bit */
238 CLEAR_BIT(FLASH
->CR
, FLASH_CR_PG
);
240 /* In case of error, stop programation procedure */
241 if (status
!= HAL_OK
)
248 /* Process Unlocked */
249 __HAL_UNLOCK(&pFlash
);
255 * @brief Program halfword, word or double word at a specified address with interrupt enabled.
256 * @note The function HAL_FLASH_Unlock() should be called before to unlock the FLASH interface
257 * The function HAL_FLASH_Lock() should be called after to lock the FLASH interface
259 * @note If an erase and a program operations are requested simultaneously,
260 * the erase operation is performed before the program one.
262 * @param TypeProgram: Indicate the way to program at a specified address.
263 * This parameter can be a value of @ref FLASH_Type_Program
264 * @param Address: Specifies the address to be programmed.
265 * @param Data: Specifies the data to be programmed
267 * @retval HAL_StatusTypeDef HAL Status
269 HAL_StatusTypeDef
HAL_FLASH_Program_IT(uint32_t TypeProgram
, uint32_t Address
, uint64_t Data
)
271 HAL_StatusTypeDef status
= HAL_OK
;
276 /* Check the parameters */
277 assert_param(IS_TYPEPROGRAM(TypeProgram
));
278 assert_param(IS_FLASH_PROGRAM_ADDRESS(Address
));
280 /* Enable End of FLASH Operation and Error source interrupts */
281 __HAL_FLASH_ENABLE_IT((FLASH_IT_EOP
| FLASH_IT_ERR
));
283 pFlash
.Address
= Address
;
286 if(TypeProgram
== TYPEPROGRAM_HALFWORD
)
288 pFlash
.ProcedureOnGoing
= FLASH_PROC_PROGRAMHALFWORD
;
289 /*Program halfword (16-bit) at a specified address.*/
290 pFlash
.DataRemaining
= 1;
292 else if(TypeProgram
== TYPEPROGRAM_WORD
)
294 pFlash
.ProcedureOnGoing
= FLASH_PROC_PROGRAMWORD
;
295 /*Program word (32-bit : 2*16-bit) at a specified address.*/
296 pFlash
.DataRemaining
= 2;
300 pFlash
.ProcedureOnGoing
= FLASH_PROC_PROGRAMDOUBLEWORD
;
301 /*Program double word (64-bit : 4*16-bit) at a specified address.*/
302 pFlash
.DataRemaining
= 4;
305 /*Program halfword (16-bit) at a specified address.*/
306 FLASH_Program_HalfWord(Address
, (uint16_t)Data
);
312 * @brief This function handles FLASH interrupt request.
315 void HAL_FLASH_IRQHandler(void)
317 uint32_t addresstmp
= 0;
319 /* Check FLASH operation error flags */
320 if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_WRPERR
) ||__HAL_FLASH_GET_FLAG(FLASH_FLAG_PGERR
))
322 /*Save the Error code*/
323 FLASH_SetErrorCode();
325 /* FLASH error interrupt user callback */
326 HAL_FLASH_OperationErrorCallback(pFlash
.Address
);
328 /* Reset address and stop the procedure ongoing*/
329 pFlash
.Address
= 0xFFFFFFFF;
330 pFlash
.ProcedureOnGoing
= FLASH_PROC_NONE
;
333 /* Check FLASH End of Operation flag */
334 if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_EOP
))
336 /* Clear FLASH End of Operation pending bit */
337 __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP
);
339 /* Process can continue only if no error detected */
340 if(pFlash
.ProcedureOnGoing
!= FLASH_PROC_NONE
)
342 if(pFlash
.ProcedureOnGoing
== FLASH_PROC_PAGEERASE
)
344 /* Nb of pages to erased can be decreased */
345 pFlash
.DataRemaining
--;
347 /* Indicate user which page address has been erased*/
348 HAL_FLASH_EndOfOperationCallback(pFlash
.Address
);
350 /* Check if there are still pages to erase*/
351 if(pFlash
.DataRemaining
!= 0)
353 /* Increment page address to next page */
354 pFlash
.Address
+= FLASH_PAGE_SIZE
;
355 addresstmp
= pFlash
.Address
;
357 /* Operation is completed, disable the PER Bit */
358 CLEAR_BIT(FLASH
->CR
, FLASH_CR_PER
);
360 FLASH_PageErase(addresstmp
);
364 /*No more pages to Erase*/
366 /*Reset Address and stop Erase pages procedure*/
367 pFlash
.Address
= 0xFFFFFFFF;
368 pFlash
.ProcedureOnGoing
= FLASH_PROC_NONE
;
371 else if(pFlash
.ProcedureOnGoing
== FLASH_PROC_MASSERASE
)
373 /* Operation is completed, disable the MER Bit */
374 CLEAR_BIT(FLASH
->CR
, FLASH_CR_MER
);
376 /*MassErase ended. Return the selected bank*/
377 /* FLASH EOP interrupt user callback */
378 HAL_FLASH_EndOfOperationCallback(0);
380 /* Stop Mass Erase procedure*/
381 pFlash
.ProcedureOnGoing
= FLASH_PROC_NONE
;
385 /* Nb of 16-bit data to program can be decreased */
386 pFlash
.DataRemaining
--;
388 /* Check if there are still 16-bit data to program */
389 if(pFlash
.DataRemaining
!= 0)
391 /* Increment address to 16-bit */
393 addresstmp
= pFlash
.Address
;
395 /* Shift to have next 16-bit data */
396 pFlash
.Data
= (pFlash
.Data
>> 16);
398 /* Operation is completed, disable the PG Bit */
399 CLEAR_BIT(FLASH
->CR
, FLASH_CR_PG
);
401 /*Program halfword (16-bit) at a specified address.*/
402 FLASH_Program_HalfWord(addresstmp
, (uint16_t)pFlash
.Data
);
406 /*Program ended. Return the selected address*/
407 /* FLASH EOP interrupt user callback */
408 if (pFlash
.ProcedureOnGoing
== FLASH_PROC_PROGRAMHALFWORD
)
410 HAL_FLASH_EndOfOperationCallback(pFlash
.Address
);
412 else if (pFlash
.ProcedureOnGoing
== FLASH_PROC_PROGRAMWORD
)
414 HAL_FLASH_EndOfOperationCallback(pFlash
.Address
-2);
418 HAL_FLASH_EndOfOperationCallback(pFlash
.Address
-6);
421 /* Reset Address and stop Program procedure*/
422 pFlash
.Address
= 0xFFFFFFFF;
423 pFlash
.ProcedureOnGoing
= FLASH_PROC_NONE
;
429 if(pFlash
.ProcedureOnGoing
== FLASH_PROC_NONE
)
431 /* Operation is completed, disable the PG, PER and MER Bits */
432 CLEAR_BIT(FLASH
->CR
, (FLASH_CR_PG
| FLASH_CR_PER
| FLASH_CR_MER
));
434 /* Disable End of FLASH Operation and Error source interrupts */
435 __HAL_FLASH_DISABLE_IT((FLASH_IT_EOP
| FLASH_IT_ERR
));
437 /* Process Unlocked */
438 __HAL_UNLOCK(&pFlash
);
444 * @brief FLASH end of operation interrupt callback
445 * @param ReturnValue: The value saved in this parameter depends on the ongoing procedure
446 * - Mass Erase: No return value expected
447 * - Pages Erase: Address of the page which has been erased
448 * - Program: Address which was selected for data program
451 __weak
void HAL_FLASH_EndOfOperationCallback(uint32_t ReturnValue
)
453 /* NOTE : This function Should not be modified, when the callback is needed,
454 the HAL_FLASH_EndOfOperationCallback could be implemented in the user file
459 * @brief FLASH operation error interrupt callback
460 * @param ReturnValue: The value saved in this parameter depends on the ongoing procedure
461 * - Mass Erase: No return value expected
462 * - Pages Erase: Address of the page which returned an error
463 * - Program: Address which was selected for data program
466 __weak
void HAL_FLASH_OperationErrorCallback(uint32_t ReturnValue
)
468 /* NOTE : This function Should not be modified, when the callback is needed,
469 the HAL_FLASH_OperationErrorCallback could be implemented in the user file
477 /** @defgroup FLASH_Exported_Functions_Group2 Peripheral Control functions
478 * @brief management functions
481 ===============================================================================
482 ##### Peripheral Control functions #####
483 ===============================================================================
485 This subsection provides a set of functions allowing to control the FLASH
493 * @brief Unlock the FLASH control register access
496 HAL_StatusTypeDef
HAL_FLASH_Unlock(void)
498 if((READ_BIT(FLASH
->CR
, FLASH_CR_LOCK
)) != RESET
)
500 /* Authorize the FLASH Registers access */
501 WRITE_REG(FLASH
->KEYR
, FLASH_FKEY1
);
502 WRITE_REG(FLASH
->KEYR
, FLASH_FKEY2
);
513 * @brief Locks the FLASH control register access
516 HAL_StatusTypeDef
HAL_FLASH_Lock(void)
518 /* Set the LOCK Bit to lock the FLASH Registers access */
519 SET_BIT(FLASH
->CR
, FLASH_CR_LOCK
);
526 * @brief Unlock the FLASH Option Control Registers access.
529 HAL_StatusTypeDef
HAL_FLASH_OB_Unlock(void)
531 if((READ_BIT(FLASH
->CR
, FLASH_CR_OPTWRE
)) == RESET
)
533 /* Authorizes the Option Byte register programming */
534 WRITE_REG(FLASH
->OPTKEYR
, FLASH_OPTKEY1
);
535 WRITE_REG(FLASH
->OPTKEYR
, FLASH_OPTKEY2
);
546 * @brief Lock the FLASH Option Control Registers access.
549 HAL_StatusTypeDef
HAL_FLASH_OB_Lock(void)
551 /* Clear the OPTWRE Bit to lock the FLASH Option Byte Registers access */
552 CLEAR_BIT(FLASH
->CR
, FLASH_CR_OPTWRE
);
558 * @brief Launch the option byte loading.
561 HAL_StatusTypeDef
HAL_FLASH_OB_Launch(void)
563 /* Clean the error context */
564 pFlash
.ErrorCode
= FLASH_ERROR_NONE
;
566 /* Set the bit to force the option byte reloading */
567 SET_BIT(FLASH
->CR
, FLASH_CR_OBL_LAUNCH
);
569 /* Wait for last operation to be completed */
570 return(FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE
));
577 /** @defgroup FLASH_Exported_Functions_Group3 Peripheral State and Errors functions
578 * @brief Peripheral Errors functions
581 ===============================================================================
582 ##### Peripheral Errors functions #####
583 ===============================================================================
585 This subsection permit to get in run-time Errors of the FLASH peripheral.
592 * @brief Get the specific FLASH error flag.
593 * @retval FLASH_ErrorCode: The returned value can be:
594 * @arg FLASH_ERROR_PG: FLASH Programming error flag
595 * @arg FLASH_ERROR_WRP: FLASH Write protected error flag
597 uint32_t HAL_FLASH_GetError(void)
599 return pFlash
.ErrorCode
;
609 /** @addtogroup FLASH_Private_Functions
613 * @brief Erase the specified FLASH memory page
614 * @param PageAddress: FLASH page to erase
615 * The value of this parameter depend on device used within the same series
619 void FLASH_PageErase(uint32_t PageAddress
)
621 /* Clean the error context */
622 pFlash
.ErrorCode
= FLASH_ERROR_NONE
;
624 /* Proceed to erase the page */
625 SET_BIT(FLASH
->CR
, FLASH_CR_PER
);
626 WRITE_REG(FLASH
->AR
, PageAddress
);
627 SET_BIT(FLASH
->CR
, FLASH_CR_STRT
);
631 * @brief Program a half-word (16-bit) at a specified address.
632 * @param Address: specifies the address to be programmed.
633 * @param Data: specifies the data to be programmed.
636 static void FLASH_Program_HalfWord(uint32_t Address
, uint16_t Data
)
638 /* Clean the error context */
639 pFlash
.ErrorCode
= FLASH_ERROR_NONE
;
641 /* Proceed to program the new data */
642 SET_BIT(FLASH
->CR
, FLASH_CR_PG
);
644 *(__IO
uint16_t*)Address
= Data
;
648 * @brief Wait for a FLASH operation to complete.
649 * @param Timeout: maximum flash operationtimeout
650 * @retval HAL_StatusTypeDef HAL Status
652 HAL_StatusTypeDef
FLASH_WaitForLastOperation(uint32_t Timeout
)
654 /* Wait for the FLASH operation to complete by polling on BUSY flag to be reset.
655 Even if the FLASH operation fails, the BUSY flag will be reset and an error
658 uint32_t tickstart
= HAL_GetTick();
660 while(__HAL_FLASH_GET_FLAG(FLASH_FLAG_BSY
))
662 if(Timeout
!= HAL_MAX_DELAY
)
664 if((Timeout
== 0) || ((HAL_GetTick() - tickstart
) > Timeout
))
671 /* Check FLASH End of Operation flag */
672 if (__HAL_FLASH_GET_FLAG(FLASH_FLAG_EOP
))
674 /* Clear FLASH End of Operation pending bit */
675 __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP
);
678 if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_WRPERR
) || __HAL_FLASH_GET_FLAG(FLASH_FLAG_PGERR
))
680 /*Save the error code*/
681 FLASH_SetErrorCode();
685 /* If there is no error flag set */
691 * @brief Set the specific FLASH error flag.
694 static void FLASH_SetErrorCode(void)
696 if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_WRPERR
))
698 pFlash
.ErrorCode
|= FLASH_ERROR_WRP
;
700 if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_PGERR
))
702 pFlash
.ErrorCode
|= FLASH_ERROR_PG
;
705 __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_WRPERR
| FLASH_FLAG_PGERR
);
712 #endif /* HAL_FLASH_MODULE_ENABLED */
722 /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/