#include <avr/io.h>
void initUART(void) {
// Formula for calculating baud
// UBRR = (16000000 / (16 * 9600)) - 1
uint16_t baudValue = 103; // round up value from calculation
UBRR0H = (uint8_t)(baudValue >> 8); // 0
UBRR0L = (uint8_t)baudValue; // 103
UCSR0B = (1 << RXEN0) | (1 << TXEN0); // enable receive and transmit register
UCSR0C = (1 << UCSZ01) | (1 << UCSZ00); // seting 8N1
}
unsigned char uartReceive(void) {
while (!(UCSR0A & (1 << RXC0))) {}
return UDR0; // get and return received data from buffer
}
unsigned char uartTransmit(unsigned char data) {
while (!(UCSR0A & (1 << UDRE0))) {}
UDR0 = data; // load data into buffer
return data;
}
int main(void) {
initUART();
while (1) {
// main loop
unsigned char receivedData = uartReceive();
uartTransmit(receivedData); // echo back received data
}
}