/**
  ******************************************************************************
  * @file     SPI_FLASH_user.c
  * @author   SINOMCU-AE
  * @brief    w25Q128 test
  * 
  *          This file provides functions to W25Q128 test.
  *    
  ******************************************************************************
  * @attention 
  *                           DISCLAIMER
  * The present firmware which is for guidance only aims at providing customers
  * with coding information regarding their products in order for them to save
  * time. As a result, SinoMCU shall not be held liable for any direct,indirect
  * or consequential damages with respect to any claims arising from the content 
  * of such firmware and/or the use made by customers of the coding information 
  * contained herein in connection with their products.
  *
  * <h2><center>&copy; Copyright (c) 2021 sinomcu All rights reserved.</center></h2>
  *
  ******************************************************************************
  */
  
/* Includes ------------------------------------------------------------------*/
#include "stdio.h"
#include "SPI_CFG.h"
#include "W25Q_Flash.h"
#include "SPI_FLASH_user.h"

/**
  * @brief  test for SPI Flash
  * @param  
  * @retval test_result,SUCCESS or ERROR
  */
ErrorStatus spi_flash_test(uint32_t address) {
  ErrorStatus test_result=SUCCESS;
  uint16_t SPI_Flash_Id = 0;
  uint8_t byte_count = 0;
  
  uint8_t WriteBuffer[SPI_FLASH_TEST_BUFF_LEN]={0},ReadBuffer[SPI_FLASH_TEST_BUFF_LEN]={0};   // buffer for write and read

  SPI_Flash_Id = SPI_Flash_ReadID(); 
  printf("\r\n--Inf: SPI Flash Device ID:0x%X.",SPI_Flash_Id);

  SPI_FLASH_Erase_Sector(address);                                                            // erase sector
  printf("\r\n--Inf: SPI Flash Erase Sector Finish,Sector Address:0x%X.", (address & 0xFFFFF000));

  for(byte_count =0; byte_count < SPI_FLASH_TEST_BUFF_LEN;byte_count++) {                     // init write buffer 0-63
    WriteBuffer[byte_count] = byte_count;
  }
  SPI_FLASH_Write_Page(address, WriteBuffer,SPI_FLASH_TEST_BUFF_LEN);                         // write to flash
  printf("\r\n--Inf: SPI Flash Wirte finish, Start address:0x%X ,Len:%d", address,SPI_FLASH_TEST_BUFF_LEN);  

  SPI_FLASH_Read(address,ReadBuffer,SPI_FLASH_TEST_BUFF_LEN);                                 // read from flash
  printf("\r\n--Inf: SPI Flash Read finish, Start address:0x%X ,Len:%d", address,SPI_FLASH_TEST_BUFF_LEN); 

  for(byte_count =0; byte_count < SPI_FLASH_TEST_BUFF_LEN;byte_count++) {                     //compare write and read
    if( ReadBuffer[byte_count] != WriteBuffer[byte_count]) {
      test_result = ERROR;
      break;
    }
  }

  if(test_result == ERROR) {
    printf("\r\n**Error: SPI Flash Test ERROR! \r\n");
  } else {
    printf("\r\n--Inf: SPI Flash Test success. \r\n");
  }
  
  return test_result;
}

/******************************** END OF FILE *********************************/
