aboutsummaryrefslogtreecommitdiff
path: root/kernel/uart.c
blob: cdfaf73a94d0fb8ff407828e3aa7d6bd70d7a4ab (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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
/* $Id$ */
/*
 * Copyright (c) 2011 Dimitri Sokolyuk <demon@dim13.org>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#ifndef BAUD
#warning "BAUD not set, fallback to default"
#define BAUD	9600
#endif

#include <inttypes.h>
#include <stdio.h>
#include <avr/io.h>
#include <avr/wdt.h>
#include <avr/interrupt.h>
#include <util/setbaud.h>
#include "kernel.h"
#include "tasks.h"

int
uart_putchar(char c)
{
	if (c == '\n')
		uart_putchar('\r');
	loop_until_bit_is_set(UCSRA, UDRE);
	UDR = c;

	return 0;
}

int
uart_getchar(void)
{
	char c;

#if 0	/* BLOCKING */
	loop_until_bit_is_set(UCSRA, RXC);
#else
	if (bit_is_clear(UCSRA, RXC))
		return 0;
#endif

	if (bit_is_set(UCSRA, FE))
		return -2;		/* EOF */
	if (bit_is_set(UCSRA, DOR))
		return -1;		/* ERR */
	c = UDR;

	uart_putchar(c);		/* ECHO */

	switch (c) {
	case '\r':
		c = '\n';
		break;
	case '\t':
		c = ' ';
		break;
	default:
		break;
	}

	return c;
}

#if USE_RXCIE
ISR(SIG_UART_RECV)
{
	uint8_t	c = UDR;
	uint8_t *p = 0;

	switch (c) {
	case 'R':	/* reboot */
		wdt_enable(WDTO_15MS);
		break;
	case 'D':	/* dump */
		while (p <= (uint8_t *)RAMEND)
			uart_putchar(*p++);
		break;
	case 'T':
		UCSRB |= _BV(UDRIE);
		break;
	case 't':
		UCSRB &= ~_BV(UDRIE);
		break;
	case '\r':
	case '\n':
		break;
	default:
		uart_putchar('?');
		break;
	}
}

ISR(SIG_UART_DATA)
{
	uint8_t r = running();

	UDR = r ? '0' + r : '.';
}
#endif

void
init_uart(void)
{
	UCSRB = _BV(RXEN) | _BV(TXEN);
#if USE_RXCIE
	UCSRB |= _BV(RXCIE);
#endif
	UBRRH = UBRRH_VALUE;
	UBRRL = UBRRL_VALUE;
	UCSRA &= ~_BV(U2X);
}