#include "bsp_uart2.h"
#include "wb32l003.h"

/**
  * @name   uart2_init
  * @brief  Initializes the UART2 peripheral.
  * @param  apbclk: Specifies the clock frequency of the APB where the UART resides.
  * @param  baud: Specifies the baud rate for communication.
  * @retval None
  */
void uart2_init(uint32_t apbclk, uint32_t baud)
{
  uint32_t tmp;

  /* Enable GPIOC and UART2 clock */
  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOC, ENABLE);
  RCC_APBPeriphClockCmd(RCC_APBPeriph_UART2, ENABLE);

  /* Reset UART2 */
  RCC_APBPeriphResetCmd(RCC_APBPeriph_UART2, ENABLE);
  RCC_APBPeriphResetCmd(RCC_APBPeriph_UART2, DISABLE);

  /*
    PC3 UART2_TX
    PC4 UART2_RX
   */
  GPIO_Init(GPIOC, GPIO_Pin_3 | GPIO_Pin_4, GPIO_PUPD_NOPULL | GPIO_OTYPE_PP | GPIO_SPEED_HIGH | GPIO_AF5);

  /* Configure UART2 */
  tmp = UART2->SCON;
  tmp |= (UART_SCON_DBAUD | (0x01 << 6) | UART_SCON_REN);
  UART2->SCON = tmp;

  tmp = UART2->BAUDCR;
  tmp = ((((2 * apbclk) / (32 * baud) - 1) & 0xFFFF) | (0x01 << 16));
  UART2->BAUDCR = tmp;

  tmp = UART2->SCON;
  tmp |= (UART_SCON_TIEN | UART_SCON_RIEN);
  UART2->SCON = tmp;
}

/**
  * @name   uart2_send
  * @brief  Send data through UART2
  * @param  buffer: Specifies a buffer pointer to the data to be sent.
  * @param  length: Specifies the length of the data to send.
  * @retval None
  */
void uart2_send(const uint8_t* buffer, uint32_t length)
{
  while (length)
  {
    UART2->SBUF = *buffer;
    while (!(UART2->INTSR & UART_INTSR_TI))
      ;
    UART2->INTCLR |= UART_INTCLR_TICLR_Msk;
    buffer++;
    length--;
  }
}
