#include "onchip_flash.h"



/*!
    \brief      Flash_erase_sector
    \param[in]  sectorNo
    \param[out] none
    \retval     none
    \note       LH  @2022.07.01
*/
uint8_t OnChip_Flash_erase_sector(uint16_t sectorNo)
{
  //解锁flash
  fmc_unlock();
  //清除标志位
  fmc_flag_clear(FMC_FLAG_END | FMC_FLAG_OPERR | FMC_FLAG_WPERR | FMC_FLAG_PGMERR | FMC_FLAG_PGSERR);
  if(FMC_READY ==fmc_sector_erase(sectorNo))
  {
    fmc_flag_clear(FMC_FLAG_END | FMC_FLAG_OPERR | FMC_FLAG_WPERR | FMC_FLAG_PGMERR | FMC_FLAG_PGSERR);
    fmc_lock();
    return 0;  // 成功
  }else{
    fmc_flag_clear(FMC_FLAG_END | FMC_FLAG_OPERR | FMC_FLAG_WPERR | FMC_FLAG_PGMERR | FMC_FLAG_PGSERR);
    fmc_lock();
    return 1;  //错误
  }
}

/*!
    \brief      OnChip_Flash_read_one_byte
    \param[in]  address
    \param[out] byte
    \retval     none
    \note       LH  @2022.07.01
*/
uint8_t OnChip_Flash_read_one_byte(uint32_t address)
{
   return REG8(address);
}


/*!
    \brief      OnChip_Flash_read_half_word
    \param[in]  address
    \param[out] half_word
    \retval     none
    \note       LH  @2022.07.01
*/
uint16_t OnChip_Flash_read_half_word(uint32_t address)
{
   return REG16(address);
}


/*!
    \brief      OnChip_Flash_read_one_word
    \param[in]  address
    \param[out] one_word
    \retval     none
    \note       LH  @2022.07.01
*/
uint32_t OnChip_Flash_read_one_word(uint32_t address)
{
   return REG32(address);
}



/*!
    \brief      Flash_read_in_add
    \param[in]  address
    \param[in]  cnt
    \param[in]  bBuf
    \param[out] none
    \retval     none
    \note       LH  @2022.07.01
*/
void OnChip_Flash_read_in_add(uint32_t address,uint16_t cnt,uint8_t*bBuf)
{
  int size=0;
  U32 R_addr = 0;
  R_addr = address;

  for(size=0;size<cnt;size++)
  {//按字节读取
    *bBuf = OnChip_Flash_read_one_byte(R_addr);
    bBuf++;
    R_addr++;
  }
  
}



/*!
    \brief      Flash_write_byte
    \param[in]  address
    \param[in]  cnt
    \param[in]  buf[]
    \param[out] none
    \retval     none
    \note       LH  @2022.07.01
*/
uint8_t OnChip_Flash_write_byte(uint32_t address,uint16_t cnt, uint8_t buf[])
{//在写之前需要先进行对应扇区擦除
  int size;
  uint32_t W_addr = 0;
  W_addr = address;
  fmc_unlock();
  for(size=0;size<cnt;size++)
  {
    if(FMC_READY != fmc_byte_program(W_addr,buf[size]))
    {
      fmc_lock();
      return 1;
    }
      
    W_addr++;
  }
  fmc_lock();
  return 0;
}

















