aboutsummaryrefslogtreecommitdiff
path: root/uart.c
blob: 5edac915706d8dce95e4a24376f4c733c4b3370a (plain)
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include "common.h"

#include <stdio.h>
#include <avr/io.h>

#include "uart.h"

/* blocking uart send
 */
static void uartSend (unsigned char data) {
	/* Wait for empty transmit buffer */
	while (!( UCSR0A & (1<<UDRE0)));
	/* Put data into buffer, sends the data */
	UDR0 = data;
}

static int uartPutc (char c, FILE *stream __unused__) {
	if (c == '\n') {
		uartSend ('\r');	
	}
	uartSend (c);
	return 0;
}

static FILE mystdout = FDEV_SETUP_STREAM (uartPutc, NULL, _FDEV_SETUP_WRITE);

void uartInit () {
	UBRR0H = 0;
#if F_CPU == 1000000
	/* Set baud rate (9600, double speed) */
	UBRR0L = 12;
#elif F_CPU == 4000000
	/* Set baud rate (9600, double speed) */
	UBRR0L = 51;
#elif F_CPU == 8000000
	/* baudrate 38.4k */
	UBRR0L = 25;
#else
#error "cpu speed not supported"
#endif
	/* enable double speed mode */
	UCSR0A = (1 << U2X0);
	/* Enable receiver and transmitter */
	UCSR0B = (1 << RXEN0) | (1 << TXEN0);
	/* Set frame format: 8 data, 1 stop bit, even parity */
	UCSR0C = (1<<UPM01) | (0 << UPM00) | (0<<USBS0)|(3<<UCSZ00);

	/* redirect stdout/stderr */
	stdout = &mystdout;
	stderr = &mystdout;
}

#if 0
/* unused */
static unsigned char uartReceive () {
	/* Wait for data to be received */
	while ( !(UCSR0A & (1<<RXC0)) );
	/* Get and return received data from buffer */
	return UDR0;
}
#endif