uart.c 547 Bytes
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
#include <avr/io.h>
#include "uart.h"

void
uart_init(void)
{
	UBRR0H = 0;
	UBRR0L = 31;

	UCSR0B = _BV(RXEN0);

	// Enable pull-up resistor on RX pin
	PORTD |= _BV(PORTD0);
}

#define UART_ERROR (1<<8)

uint16_t
uart_read(void)
{
	uint8_t uart_status = UCSR0A;
	if (!(uart_status & _BV(RXC0))) {
		// No UART data available
		return UART_ERROR;
	}

	// Read data to clear all status bits
	uint8_t uart_data = UDR0;

	if (uart_status & (_BV(FE0) | _BV(DOR0) | _BV(UPE0))) {
		// There was a UART error
		return UART_ERROR;
	}

	return uart_data;
}