#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>

#include "utils.h"
#include "bitmanip.h"
#include "usart.h"

// USART
#define USART_BAUDRATE		115200

// END MACROS

void uart_init() {
	UBRR0H = (unsigned char) (BAUD_PRESCALER(USART_BAUDRATE) >> 8);				// 20.11.5 : UBRRnL and UBRRnH – USART Baud Rate Registers
	UBRR0L = (unsigned char) BAUD_PRESCALER(USART_BAUDRATE);

	UCSR0C |= ASYNCHRONOUS | PARITY_DISABLED | STOP_ONE_BIT | DATA_EIGHT_BIT;	// 20.11.4 : set Frame Format
	
	UCSR0B |= RECEIVER_ENABLED | TRANSMITTER_ENABLED;							// 20.11.3 : enable Receiver and/or Transmitter
}

void uart_tx(char c) {
	while (TEST(UCSR0A, UDRE0) == 0);											// 20.11.2 : do nothing until UDRn buffer is empty, (UDREn flag in UCSRnA register set to 1 when buffer empty)
	UDR0 = (unsigned char) c;													// 20.11.1 : Put data into buffer, UDRn – USART I/O Data Register (read and write)
}

char uart_rx(void) {
	while (TEST(UCSR0A, RXC0) == 0);											// 20.11.2 : do nothing until there are unread data in the receive buffer (UDRn), (RXCn flag in UCSRnA register set to 1 when buffer has data)
	return UDR0;																// 20.11.1 : get data in buffer, UDRn – USART I/O Data Register (read and write)
}

// send back caracters received on serial port
// `screen /dev/ttyUSB0 115200`
int main() {
	uart_init();

	char received_char;
	while(1) {
		received_char = uart_rx();
		uart_tx(received_char);
	}
}
