AVR-Playground/uart.c

33 lines
931 B
C
Raw Normal View History

2024-03-23 21:18:52 +01:00
#include "uart.h"
#include <avr/io.h>
#include <util/delay.h>
// 9600 seems to be the highest the ATmega328P can handle in this config
#define BAUD 9600
#include <util/setbaud.h>
void initUART() {
// Set baud rate
UBRR0H = (uint8_t)(F_CPU / (BAUD * 16UL) - 1) >> 8;
UBRR0L = (uint8_t)(F_CPU / (BAUD * 16UL) - 1);
// Enable receiver and transmitter
UCSR0B |= (1 << RXEN0) | (1 << TXEN0);
// Set frame format: 8 data, 1 stop bit
UCSR0C |= (1 << UCSZ01) | (1 << UCSZ00);
}
void UART_transmit(uint8_t data) {
// Wait for empty transmit buffer
while (!(UCSR0A & (1 << UDRE0)));
// Put data into buffer, sends the data
UDR0 = data;
}
void UART_println(const char *str) {
// Transmit each character until NULL character is encountered
while (*str) UART_transmit(*str++);
// Transmit carriage return and line feed characters
UART_transmit('\r');
UART_transmit('\n');
}