Universal Asynchronous Receiver/Transmitter (UART) is a simple yet powerful serial communication protocol widely used in embedded systems.
// Initialize UART
void initUART(uint32_t baudRate) {
// Calculate baud rate register value
uint16_t ubrr = F_CPU/16/baudRate - 1;
// Set baud rate
UBRR0H = (uint8_t)(ubrr>>8);
UBRR0L = (uint8_t)ubrr;
// Enable receiver and transmitter
UCSR0B = (1<<RXEN0)|(1<<TXEN0);
// Set frame format: 8data, 1stop bit
UCSR0C = (1<<UCSZ01)|(1<<UCSZ00);
}// Send a byte
void UARTsendByte(uint8_t data) {
// Wait for empty transmit buffer
while (!(UCSR0A & (1<<UDRE0)));
UDR0 = data;
}
// Receive a byte
uint8_t UARTreceiveByte() {
// Wait for data
while (!(UCSR0A & (1<<RXC0)));
return UDR0;
}