#include "stm32f0xx.h"
#include "uart.h"

void uart_init(void)
{
	GPIOA->MODER |= (2 << GPIO_MODER_MODER2_Pos)|(2 << GPIO_MODER_MODER3_Pos); // PA2 and PA3 alternate function
	GPIOA->OSPEEDR |= (3 << GPIO_OSPEEDR_OSPEEDR2_Pos)|(3 << GPIO_OSPEEDR_OSPEEDR3_Pos); // high speed
	GPIOA->AFR[0] |= (1 << GPIO_AFRL_AFRL2_Pos)|(1 << GPIO_AFRL_AFRL3_Pos); // used by USART1

	// 8 bits, 1 stop bit, no parity, baudrate 38400 @ 32 MHz
	USART1->BRR = 833;
	USART1->CR1 |= (1 << USART_CR1_TE_Pos)|(1 << USART_CR1_RE_Pos)|(1 << USART_CR1_UE_Pos); // transmitter, receiver and usart enable
}

void uart_send(uint8_t data)
{
	uint16_t time_out = 10000;

	while(!(USART1->ISR & (1 << USART_ISR_TXE_Pos)) && time_out--) // wait for TDR to be empty
		;
	USART1->TDR = data;
}

uint8_t uart_receive(void)
{
	uint16_t time_out = 10000; // watch out for slow baudrate

	while(!(USART1->ISR & (1 << USART_ISR_RXNE_Pos)) && time_out--) // wait for RDR to be full
		;

	return USART1->RDR;
}

void uart_print(char *s)
{
	while(*s != '\0')
		uart_send(*s++);
}
