stm32l071cbt6片内flash操作

今天在看片内flash的操作,发现按照下面的操作并没有写成功:

    unsigned long temp = 0x12345678;

    HAL_FLASH_Unlock();
    FLASH_PageErase(APPLICATION_B_ADDRESS)
    status = HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD,APPLICATION_B_ADDRESS,temp);
    HAL_FLASH_Lock();
HAL_StatusTypeDef HAL_FLASH_Program(uint32_t TypeProgram, uint32_t Address, uint32_t Data)
{
  HAL_StatusTypeDef status = HAL_ERROR;
  
  /* Process Locked */
  __HAL_LOCK(&pFlash);

  /* Check the parameters */
  assert_param(IS_FLASH_TYPEPROGRAM(TypeProgram));
  assert_param(IS_FLASH_PROGRAM_ADDRESS(Address));

  /* Wait for last operation to be completed */
  status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE);
  
  if(status == HAL_OK)
  {
    /* Clean the error context */
    pFlash.ErrorCode = HAL_FLASH_ERROR_NONE;

    /*Program word (32-bit) at a specified address.*/
    *(__IO uint32_t *)Address = Data;

    /* Wait for last operation to be completed */
    status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE);
  }

  /* Process Unlocked */
  __HAL_UNLOCK(&pFlash);

  return status;
}

但是下面这个函数的返回值是HAL_OK的,误导性太大了,让我一时不知道怎么去查。

status = HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD,APPLICATION_B_ADDRESS,temp);

 

我花了一下午时间对着手册寄存器去查问题,直接说结果吧:

    FLASH_EraseInitTypeDef f;
    HAL_StatusTypeDef status = HAL_OK;
    uint32_t PageError = 0;
    
    f.TypeErase = FLASH_TYPEERASE_PAGES;
    f.PageAddress = address;
    f.NbPages = page_cnt;                                
    status = HAL_FLASHEx_Erase(&f, &PageError);

erase用这个函数就没问题了,唯一的区别就是多了两个清除标志位的操作:

      FLASH_PageErase(address);

      /* Wait for last operation to be completed */
      status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE);

      /* If the erase operation is completed, disable the ERASE Bit */
      CLEAR_BIT(FLASH->PECR, FLASH_PECR_PROG);
      CLEAR_BIT(FLASH->PECR, FLASH_PECR_ERASE);

就写到这里吧。

 

转载于:https://www.cnblogs.com/kent-hu/p/8406229.html

你可能感兴趣的:(stm32l071cbt6片内flash操作)