uart.c 755 Bytes
Newer Older
1
#include <avr/io.h>
Jacob Vosmaer's avatar
Jacob Vosmaer committed
2
#include <avr/interrupt.h>
3
#include "uart.h"
Jacob Vosmaer's avatar
Jacob Vosmaer committed
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#include "buffer.h"

ISR(USART_RX_vect)
{
	uint8_t uart_status = UCSR0A;
	if (!(uart_status & _BV(RXC0))) {
		// No UART data available
		return;
	}

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

	buffer_push(uart_data);
}
24 25 26 27 28 29 30

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

Jacob Vosmaer's avatar
Jacob Vosmaer committed
31
	UCSR0B = _BV(RXEN0) | _BV(RXCIE0);
32 33 34

	// Enable pull-up resistor on RX pin
	PORTD |= _BV(PORTD0);
Jacob Vosmaer's avatar
Jacob Vosmaer committed
35 36 37

	// Globally enable interrupts
	sei();
38 39 40 41 42 43 44
}

#define UART_ERROR (1<<8)

uint16_t
uart_read(void)
{
Jacob Vosmaer's avatar
Jacob Vosmaer committed
45
	if (buffer_empty()) {
46 47 48 49
		// No UART data available
		return UART_ERROR;
	}

Jacob Vosmaer's avatar
Jacob Vosmaer committed
50 51
	return buffer_pop();
}