/* Includes ------------------------------------------------------------------*/
#include "FE82160.h"
#include "bsp_uart1.h"
#include <string.h>
#include <stdio.h>

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
uint8_t write_buf[] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09};

/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/

void delay(uint32_t ticks)
{
  while (ticks--)
    ;
}

FLASH_Status FLASH_Program(uint32_t Addr, uint8_t *Data, uint32_t Len)
{
  FLASH_Status flashstatus = FLASH_COMPLETE;

  while (Len)
  {
    flashstatus = FLASH_ProgramByte(Addr++, *Data++);
    if (flashstatus != FLASH_COMPLETE)
    {
      break;
    }
    Len--;
  }

  return flashstatus;
}

int main(void)
{
  SystemCoreClockUpdate();

  uart1_init(SystemCoreClock, 115200);

  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOD, ENABLE);

  GPIO_Init(GPIOD, GPIO_Pin_4, GPIO_MODE_OUT | GPIO_OTYPE_PP);

  FLASH_ErasePage(0x2000);
  FLASH_Program(0x2000, write_buf, sizeof(write_buf));

  if (memcmp((void *)0x2000, write_buf, sizeof(write_buf)) == 0)
  {
    printf("Flash write success.\r\n");
  }
  else
  {
    printf("Flash write failed.\r\n");
  }

  /* Infinite loop */
  while (1)
  {
    delay(1000000);
    GPIO_ToggleBits(GPIOD, GPIO_Pin_4);
  }
}

#ifdef USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */

  /* Infinite loop */
  while (1)
  {
  }
}
#endif
