#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>		// https://www.nongnu.org/avr-libc/user-manual/group__avr__interrupts.html

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

// USART
#define USART_BAUDRATE					115200

// TIMER
#define PERIOD							2000
#define PRESCALE_VALUE					1024		// can be 1, 8, 64, 256, 1024

// 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 | INTERRUPT_RECEIVER_ENABLED;	// 20.11.3 : enable Receiver and Transmitter, and interrupt on receiver
}

// 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)
// }

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)
}

// send back caracters received on serial port with case toggling, using interupt and empty infinite loop
// `screen /dev/ttyUSB0 115200`
int main() {
	uart_init();

	SREG |= ENABLE_GLOBAL_INTERRUPT;												// 7.3.1 : Status Register, bit 7 : I – Global Interrupt Enable

	while(1);
}

ISR(USART_RX_vect) {																// Table 12-7 : we select the code for USART Receive
	// char received_char = uart_rx();
	char received_char = UDR0;														// Read received character
	uart_tx(SWITCH_CASE(received_char));											// Toggle case and send back
}
