From 8c5f723619e382247ba70dca5125d5a2bac5c52a Mon Sep 17 00:00:00 2001 From: Arti Zirk Date: Sat, 10 Sep 2016 00:23:43 +0300 Subject: [PATCH] Add uart functions from https://github.com/tuupola/avr_demo --- src/uart.c | 40 ++++++++++++++++++++++++++++++++++++++++ src/uart.h | 9 +++++++++ 2 files changed, 49 insertions(+) create mode 100644 src/uart.c create mode 100644 src/uart.h diff --git a/src/uart.c b/src/uart.c new file mode 100644 index 0000000..e98fb64 --- /dev/null +++ b/src/uart.c @@ -0,0 +1,40 @@ +#include +#include + +#ifndef F_CPU +#define F_CPU 16000000UL +#endif + +#ifndef BAUD +#define BAUD 9600 +#endif +#include + +/* http://www.cs.mun.ca/~rod/Winter2007/4723/notes/serial/serial.html */ + +void uart_init(void) { + UBRR0H = UBRRH_VALUE; + UBRR0L = UBRRL_VALUE; + +#if USE_2X + UCSR0A |= _BV(U2X0); +#else + UCSR0A &= ~(_BV(U2X0)); +#endif + + UCSR0C = _BV(UCSZ01) | _BV(UCSZ00); /* 8-bit data */ + UCSR0B = _BV(RXEN0) | _BV(TXEN0); /* Enable RX and TX */ +} + +void uart_putchar(char c, FILE *stream) { + if (c == '\n') { + uart_putchar('\r', stream); + } + loop_until_bit_is_set(UCSR0A, UDRE0); + UDR0 = c; +} + +char uart_getchar(FILE *stream) { + loop_until_bit_is_set(UCSR0A, RXC0); + return UDR0; +} diff --git a/src/uart.h b/src/uart.h new file mode 100644 index 0000000..b2c6cde --- /dev/null +++ b/src/uart.h @@ -0,0 +1,9 @@ +void uart_putchar(char c, FILE *stream); +char uart_getchar(FILE *stream); + +void uart_init(void); + +/* http://www.ermicro.com/blog/?p=325 */ + +FILE uart_output = FDEV_SETUP_STREAM(uart_putchar, NULL, _FDEV_SETUP_WRITE); +FILE uart_input = FDEV_SETUP_STREAM(NULL, uart_getchar, _FDEV_SETUP_READ);