summaryrefslogtreecommitdiff
path: root/serial.c
blob: 418a97df2ff25f0c7815469c0bd55603e0e64968 (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
/*
 * Copyright 2012 (C) Christian Franke <nobody at nowhere dot ws>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with This program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#define BAUD 38400

#include <avr/interrupt.h>
#include <avr/io.h>
#include <util/setbaud.h>
#include <stdint.h>
#include <string.h>

#include "serial.h"


static char output_buffer[512];
static uint16_t output_offset = 0;
static uint16_t output_end = 0;

static char input_buffer[512];
static uint16_t input_end = 0;

static uint8_t verbose = 0;

void serial_send(const char *buffer, uint16_t len, uint8_t urgent)
{
	if (!urgent && !verbose)
		return;

	cli();

	if (sizeof(output_buffer) - output_end < len) {
		memmove(output_buffer, output_buffer + output_offset, output_end -
				output_offset);
		output_end -= output_offset;
		output_offset = 0;
	}

	uint16_t size = len;

	if (size > sizeof(output_buffer) - output_end)
		size = sizeof(output_buffer) - output_end;

	memcpy(&output_buffer[output_end], buffer, size);

	uint8_t send_needed = output_end == output_offset;

	output_end += size;
	sei();

	if (send_needed) {
		output_offset++;
		UDR = output_buffer[output_offset - 1];
	}
}

ISR(USART_TXC_vect)
{
	if (output_end == output_offset)
		return;

	UDR = output_buffer[output_offset];
	output_offset++;
}

ISR(USART_RXC_vect)
{
	if (input_end == sizeof(input_buffer))
		input_end = 0;

	input_buffer[input_end++] = UDR;
	input_end -= serial_rx_cb(input_buffer, input_end);
}

void serial_toggle_verbose(void)
{
	verbose = 1 - verbose;
}

void serial_init(void)
{
	UBRRH = UBRRH_VALUE;
	UBRRL = UBRRL_VALUE;
	UCSRA = 0x00;
	UCSRB = (1 << RXCIE) | (1 << TXCIE) | (1 << RXEN) | (1 << TXEN);
	UCSRC = (1 << URSEL) | (1 << UCSZ1) | (1 << UCSZ0);
}