#include "uart.h"

#include "ch32v003fun.h"

// Write multiple chars to UART
int _write(int fd, const char *buf, int size) {
  for (int i = 0; i < size; i++) {
    while (!(USART2->STATR & USART_FLAG_TC));  // Wait for transmission complete
    USART2->DATAR = *buf++;                    // Send character
  }
  return size;
}

// Write a single char to UART
int putchar(int c) {
  while (!(USART2->STATR & USART_FLAG_TC));  // Wait for transmission complete
  USART2->DATAR = (uint8_t)c;                // Send character
  return 1;
}

void setup_uart(int uart_brr) {
  // RCC->APB2PCENR |= RCC_APB2Periph_GPIOA;   // Enable GPIOA on APB2
  RCC->APB1PCENR |= RCC_APB1Periph_USART2;  // Enable USART2 on APB1

  GPIOA->CFGLR &= ~(0xf << (4 * 2));  // Clear bits for PA2
  GPIOA->CFGLR |= (GPIO_Speed_10MHz | GPIO_CNF_OUT_PP_AF)
                  << (4 * 2);  // Set PA2 as AF

  // USART configuration: 115200 baud rate, 8 data bits, no parity, 1 stop bit
  USART2->CTLR1 = USART_WordLength_8b | USART_Parity_No | USART_Mode_Tx;
  USART2->CTLR2 = USART_StopBits_1;
  USART2->CTLR3 = USART_HardwareFlowControl_None;

  USART2->BRR = uart_brr;
  // Enable USART2
  USART2->CTLR1 |= CTLR1_UE_Set;
}