Detailed explanation of reading and writing flash in STM32

Publisher:caoxians4589Latest update time:2018-09-11 Source: eefocusKeywords:STM32 Reading articles on mobile phones Scan QR code
Read articles on your mobile phone anytime, anywhere


1: To program the STM32 internal FLASH, you need to follow the following process:

  1. Flash unlock

  2. Clear related flags

  3. Erase FLASH (the reason for erasing first and then writing is for the convenience of industrial production, that is, the convenience of physical implementation)

  4. Write to FLASH

  5. Lock FLASH

 

(1) Get status: FLASH_Status FLASH_GetStatus(void);

The return value is defined by the enumeration type.

 

 typedef enum

   FLASH_BUSY = 1,  //忙

   FLASH_ERROR_PG, //Programming error

   FLASH_ERROR_WRP, //Write protection error

   FLASH_COMPLETE, // Operation completed

   FLASH_TIMEOUT // Operation timeout

 }FLASH_Status;

 

(2) FLASH_Unlock(); //Unlock function (must be unlocked before writing to the flash)

(3) FLASH_ClearFlag(); // Clear all existing flags

(4) There are three erase functions:

FLASH_Status FLASH_ErasePage(uint32_t Page_Address);

FLASH_Status FLASH_EraseAllPages(void);

FLASH_Status FLASH_EraseOptionBytes(void);

 

(5) Write function:

FLASHStatus FLASH_ProgramWord(uint32_t Address, uint32_t Data); //32-bit word write function

FLASHStatus FLASH_ProgramHalfWord(uint32_t Address,uint32_t Data); //16-bit half-word write

FLASHStatus FLASH_ProgramOptionByteData(uint32_t Address,uint32_t Data); //User byte write

 

int write_flash(u32 StartAddr,u16 *buf,u16 len)

{

    volatile FLASH_Status FLASHStatus;

u32 FlashAddr;

len=(len+1)/2;

FLASH_Unlock(); //1. Unlock function (must be unlocked before writing to the flash)

    FLASH_ClearFlag(FLASH_FLAG_BSY | FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPERR); //2. Clear all existing flags

FlashAddr=StartAddr;

FLASH_ErasePage(StartAddr); //3. Erase a flash page

    while(len--)

    {

 

      //FLASH_ProgramHalfWord is a write function, the return value is the status of the flash (5 types)

      FLASHStatus = FLASH_ProgramHalfWord(FlashAddr,*buf++);

      if (FLASHStatus != FLASH_COMPLETE) //FLASH_COMPLETE indicates flash completion

      {

        //printf("FLSH :Error %08X\n\r",FLASHStatus);

        return -1;

      }

      FlashAddr += 2;

    }

FLASH_Lock();

return 0;

}

 

2. FLASH reading method

 

    *(uint32_t *)0x8000000; //read a word

  *(uint8_t *)0x8000000; //read a byte;

  *(uint16_t *)0x8000000; //read half word;  

  Example:

  uint8_t data;

  data = *(uint8_t *)0x8000000; // read the data at address 0x8000000 in FLASH

 

 

int read_flash(u32 StartAddr,u32 *buf,u16 len) //Read one word 4 bytes at a time

{

len=(len+3)/4;

while(len--)

        {

*buf=*(__IO uint32_t *)StartAddr;

                 StartAddr=StartAddr+4;

                 buf++;

}

        return 0;

}

 

Three: Several useful sub-functions

/*

Function: Write data to the specified address

Parameter description: addr: address of the FLASH page to be written

          p: the address of the variable to be written (the array must be of type uint8_t and the number of elements must be an even number)

          Byte_Num: The number of bytes written to the variable (must be an even number)

*/

  void FLASH_WriteByte(uint32_t addr , uint8_t *p , uint16_t Byte_Num)

  {

          uint32_t HalfWord;

          Byte_Num = Byte_Num/2;

          FLASH_Unlock();

          FLASH_ClearFlag(FLASH_FLAG_BSY | FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR);

          FLASH_ErasePage(addr);

          while(Byte_Num --)

          {

                  HalfWord=*(p++);

                  HalfWord|=*(p++)<<8;

                  FLASH_ProgramHalfWord(addr, HalfWord);

                  addr += 2;

          }

          FLASH_Lock();

  }

 

  example:

  uint8_t data[100];

  FLASH_WriteByte(0x8000000, data, 100);/*The data in the array data is written into FLASH*/

 

/*

Function: Read data from the specified address

Parameter description: addr address read from FLASH

          p is the address of the variable to be stored after reading (the array must be of type uint8_t)

          Byte_Num The number of bytes to be read

*/

  void FLASH_ReadByte(uint32_t addr , uint8_t *p , uint16_t Byte_Num)

  {

    while(Byte_Num--)

    {

     *(p++)=*((uint8_t*)addr++);

    }

  }

  example:

  uint8_t data[101];

  FLASH_ReadByte(0x8000001, data, 101);/*The data in FLASH is read into the array data*/

hardware_conf.h中:

//64 flash

#define ADDRESS_START_ADDR ((u32)0x0800EC00) //59: store domain name and port number

#define TIME_START_ADDR ((u32)0x0800F000) //60: storage time

#define KEYS_START_ADDR ((u32)0x0800F400) //61: store various keys

#define MACHINEID_START_ADDR ((u32)0x0800F800) //62: store machine code

#define VERSION_START_ADDR ((u32)0x0800FC00) //63: store version number

 

In main():

//Get the flash content

void getFlash()

{

      /*Read machine code*/

    u8 machineId[19]="";

    read_flash(MACHINEID_START_ADDR, (u32 *) machineId, 19);

    strncpy(MachineID_Default, machineId, 18);

    

    /*Read time*/   

    u8 times[20]="";

    read_flash(TIME_START_ADDR, (u32 *) times, 20);

    

    char timeKey[2]="";

    strncpy(timeKey, times, 1);

 

    

    /*Read keys*/

    u8 out_data[220];

    read_flash(KEYS_START_ADDR, (u32 *) out_data, 220);

  }

    

//Write various keys to flash

int getAllMessage() 

{

    char in_data[220];

    //The following are the variables that falsh needs to store

    sprintf(in_data, "%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s",isFisrt,community_code,address,swipe,code_overtime,myKey1,Private_Key,check_pw);

    if(strlen(in_data)==96&&in_data[0]=='N' &&in_data[1]=='\n'&&in_data[63]=='\n'&&in_data[65]=='\n'&&in_data[69]=='\n'&&in_data[75]=='\n'&&in_data[82]=='\n'&&in_data[89]=='\n')

    {

      write_flash(KEYS_START_ADDR, (u16 *) in_data, 220);

      ACCLOG("write keys success\n");

      return 1;

    }else{

      ACCLOG("write keys fail...\n");

      return 0;

    }

}


Keywords:STM32 Reference address:Detailed explanation of reading and writing flash in STM32

Previous article:Detailed explanation of the meaning of the five states of FLASH_Status in STM32
Next article:STM32L0 Development Notes 13: 485 bus send and receive switching time

Recommended ReadingLatest update time:2024-11-16 12:44

STM32 PWM output experiment
First, some necessary declarations #include stm32f10x.h #include "pwm.h"u32 Sys_Clk=1000000;u16 pwm1_2_Freqz;//Frequency of pwm wave 1, 2 output port u16 pwm3_4_Freqz;//Frequency of pwm wave 3, 4 output port u16 TIM2_PERIOD;//Number of timer jump cycles u16 TIM4_PERIOD;u16 CCR_VAL1;//Value of the timer comparison reg
[Microcontroller]
STM32 PWM output experiment
Can STM32 run Linux?
There are two types of operating systems: those with MMU and those without MMU The ones that use MMU are Windows, MacOS, Linux, Android, and the ones that don't use MMU are FreeRTOS, VxWorks, and ucOS... There are two types of CPUs, with and without MMU. The ones with MMU are Cortex-A series, ARM9, and ARM11 se
[Microcontroller]
STM32 Getting Started with GPIO (STM32F030F4P6 based on CooCox IDE) (Part 3)
First directly on the code #include "stm32f0xx.h" #include "stm32_lib/inc/stm32f0xx_rcc.h" #include "stm32_lib/inc/stm32f0xx_gpio.h"   int main(void) { //1. Enable the clock RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE); //Define an IO GPIO_InitTypeDef PORT_LED; //Set IO pin, mode, output type, speed PORT
[Microcontroller]
14 Flash Memory Controller (FMC)
14.1 Overview The NuMicro M051 series has 64K/32K/16K/8K bytes of on-chip FLASH EEPROM for storing application programs (APROM). Users can update the program in FLASH through ISP/IAP. In-system programming (ISP) allows users to update the program in the chip soldered on the PCB board. After power-on, th
[Microcontroller]
14 Flash Memory Controller (FMC)
STM32 disable or enable general interrupt
When using STM32, it is sometimes necessary to disable global interrupts. For example, the external interrupts need to be disabled during the MCU upgrade process to prevent the upgrade from failing due to external interrupt triggering during the upgrade process. ARM MDK provides the following two interfaces to disab
[Microcontroller]
MDK development environment STM32 startup file _main function analysis
======================================================================== ** Section #1 'ER_IROM1' (SHT_PROGBITS)     Size   : 1008 bytes (alignment 4)     Address: 0x08000000     $d.realdata     RESET     __Vectors ; starting address of vector table         0x08000000: 20000460 `.. DCD 536872032; Stack pointer addr
[Microcontroller]
Using STM32 external interrupt to drive four-way digital touch sensor module
First, let me introduce the external interrupts of STM32. Of course, this is not my summary. This is a learning document that I found among so many blogs and I think it is a good summary. Let's learn it first! In STM32, each GPIO can trigger an external interrupt, but the GPIO interrupt is a unit of group bit, and o
[Microcontroller]
Using STM32 external interrupt to drive four-way digital touch sensor module
stm32 study notes--spi and iic
Regarding the issue of changing the program mentioned last time, //Read ADXL345 registers //addr: register address //Return value: the value read u8 ADXL345_RD_Reg(u8 addr) { u8 temp=0;   IIC_Start();      IIC_Send_Byte(ADXL_WRITE); //Send device write instruction   temp=IIC_Wait_Ack();           IIC
[Microcontroller]
Latest Microcontroller Articles
  • Download from the Internet--ARM Getting Started Notes
    A brief introduction: From today on, the ARM notebook of the rookie is open, and it can be regarded as a place to store these notes. Why publish it? Maybe you are interested in it. In fact, the reason for these notes is ...
  • Learn ARM development(22)
    Turning off and on interrupts Interrupts are an efficient dialogue mechanism, but sometimes you don't want to interrupt the program while it is running. For example, when you are printing something, the program suddenly interrupts and another ...
  • Learn ARM development(21)
    First, declare the task pointer, because it will be used later. Task pointer volatile TASK_TCB* volatile g_pCurrentTask = NULL;volatile TASK_TCB* vol ...
  • Learn ARM development(20)
    With the previous Tick interrupt, the basic task switching conditions are ready. However, this "easterly" is also difficult to understand. Only through continuous practice can we understand it. ...
  • Learn ARM development(19)
    After many days of hard work, I finally got the interrupt working. But in order to allow RTOS to use timer interrupts, what kind of interrupts can be implemented in S3C44B0? There are two methods in S3C44B0. ...
  • Learn ARM development(14)
  • Learn ARM development(15)
  • Learn ARM development(16)
  • Learn ARM development(17)
Change More Related Popular Components

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

About Us Customer Service Contact Information Datasheet Sitemap LatestNews


Room 1530, 15th Floor, Building B, No.18 Zhongguancun Street, Haidian District, Beijing, Postal Code: 100190 China Telephone: 008610 8235 0740

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京ICP证060456号 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号