Skip to content

Commit 1ae9f0c

Browse files
committed
[examples] Add simple uart driver for examples
1 parent b1bac95 commit 1ae9f0c

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

examples/common/uart.cpp

+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/*
2+
* Copyright (c) 2018, Christopher Durand
3+
*
4+
* This file is part of the modm project.
5+
*
6+
* This Source Code Form is subject to the terms of the Mozilla Public
7+
* License, v. 2.0. If a copy of the MPL was not distributed with this
8+
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
9+
*/
10+
// ----------------------------------------------------------------------------
11+
12+
#define BAUD 9600
13+
14+
#ifndef F_CPU
15+
#error "F_CPU must be defined!"
16+
#endif
17+
18+
#include <util/setbaud.h>
19+
20+
#include <avr/io.h>
21+
#include <cstdio>
22+
23+
// naive unbuffered uart implementation for C standard IO
24+
25+
static int
26+
uart_putc(char c, [[maybe_unused]] FILE* stream)
27+
{
28+
loop_until_bit_is_set(UCSR0A, UDRE0);
29+
UDR0 = c;
30+
return 0;
31+
}
32+
33+
static int
34+
uart_getc([[maybe_unused]] FILE* stream)
35+
{
36+
loop_until_bit_is_set(UCSR0A, RXC0);
37+
return UDR0;
38+
}
39+
40+
// constructor attribute: call function before main
41+
static void uart_init() __attribute__ ((constructor, used));
42+
43+
static void
44+
uart_init()
45+
{
46+
UBRR0H = UBRRH_VALUE;
47+
UBRR0L = UBRRL_VALUE;
48+
49+
#if USE_2X
50+
UCSR0A |= _BV(U2X0);
51+
#else
52+
UCSR0A &= ~(_BV(U2X0));
53+
#endif
54+
55+
UCSR0C = _BV(UCSZ01) | _BV(UCSZ00);
56+
UCSR0B = _BV(RXEN0) | _BV(TXEN0);
57+
58+
static FILE uart_output = {};
59+
static FILE uart_input = {};
60+
61+
fdev_setup_stream(&uart_output, uart_putc, nullptr, _FDEV_SETUP_WRITE);
62+
fdev_setup_stream(&uart_input, nullptr, uart_getc, _FDEV_SETUP_READ);
63+
64+
stdout = &uart_output;
65+
stdin = &uart_input;
66+
}

0 commit comments

Comments
 (0)