/* Includes ------------------------------------------------------------------*/
#include "FE82160.h"

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
UART_InitTypeDef UART_InitStructure;

/* Private function prototypes -----------------------------------------------*/
void UART_Transmit(UART_TypeDef* UARTx, uint8_t *pData, uint16_t Size);

/* Private functions ---------------------------------------------------------*/

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

int main(void)
{
  uint32_t value;

  SystemCoreClockUpdate();

  /*
    PD5 UART1_TX
    PD6 UART1_RX
   */
  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOD, ENABLE);
  GPIO_Init(GPIOD, GPIO_Pin_5 | GPIO_Pin_6, GPIO_PUPD_NOPULL | GPIO_OTYPE_PP | GPIO_SPEED_HIGH | GPIO_AF7);

  /* Enable UART1 */
  RCC_APBPeriphClockCmd(RCC_APBPeriph_UART1, ENABLE);
  UART_DeInit(UART1);

  /* UART1 Config Init Param */
  UART_InitStructure.UART_BandDouble = UART_BandDouble_Enable;
  UART_InitStructure.UART_BaudRate = 115200;
  UART_InitStructure.UART_BaudRateMode = UART_BaudRateMode_Self;
  UART_InitStructure.UART_WordLength = UART_WordLength_8b;
  UART_Init(UART1, &UART_InitStructure);

  UART_Cmd(UART1, ENABLE);

  UART_Transmit(UART1, "Please enter some character.\r\n", sizeof("Please enter some character.\r\n"));

  UART_ITConfig(UART1, UART_IT_TI | UART_IT_RI, ENABLE);

  /* Infinite loop */
  while (1)
  {
    while (UART_GetFlagStatus(UART1, UART_FLAG_RI) == RESET)
      ;
    value = UART_ReadData(UART1);
    UART_ClearFlag(UART1, UART_FLAG_RI);

    UART_WriteData(UART1, value);
    while (UART_GetFlagStatus(UART1, UART_FLAG_TI) == RESET)
      ;
    UART_ClearFlag(UART1, UART_FLAG_TI);
  }
}

void UART_Transmit(UART_TypeDef *UARTx, uint8_t *pData, uint16_t Size)
{
  uint16_t Count;

  if (UARTx == UART1)
    NVIC_DisableIRQ(UART1_IRQn);
  if (UARTx == UART2)
    NVIC_DisableIRQ(UART2_IRQn);

  UART_ITConfig(UARTx, UART_IT_TI, ENABLE);

  Count = Size;
  while (Count--)
  {
    UART_WriteData(UARTx, *pData++);
    while (UART_GetFlagStatus(UARTx, UART_FLAG_TI) == RESET)
      ;
    UART_ClearFlag(UARTx, UART_FLAG_TI);
  }

  UART_ITConfig(UARTx, UART_IT_TI, DISABLE);
}

#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
