/*
 * ----------------------------------------------------------------------------
 * "THE BEER-WARE LICENSE" (Revision 42):
 * <joerg@FreeBSD.ORG> wrote this file.  As long as you retain this notice you
 * can do whatever you want with this stuff. If we meet some day, and you think
 * this stuff is worth it, you can buy me a beer in return.        Joerg Wunsch
 * ----------------------------------------------------------------------------
 *
 */
#ifndef UART_H
#define UART_H
#include <avr/io.h>

/* attiny2313 -> at90s2313 compatibility */
#define UBRRL UBRR
#define UCSRB UCR
#define UCSRA USR

/*
 * Initialize the UART to UART_BAUD Bd, tx/rx, 8N1.
 */
static inline void uart_init(void) {
#if F_CPU < 2000000UL && defined(U2X)
    UCSRA = _BV(U2X);             /* improve baud rate error by using 2x clk */
    UBRRL = (F_CPU / (8UL * UART_BAUD)) - 1;
#else
    UBRRL = (F_CPU / (16UL * UART_BAUD)) - 1;
#endif
    UCSRB = _BV(TXEN) | _BV(RXEN); /* tx/rx enable */
}

/*
 * Send character c down the UART Tx, wait until tx holding register
 * is empty.
 */
static void uart_putchar(uint8_t c) {
    loop_until_bit_is_set(UCSRA, UDRE);
    UDR = c;
}

/*
 * Receive a character from the UART Rx.
 */
static uint8_t uart_getchar(void) {
    loop_until_bit_is_set(UCSRA, RXC);
    return UDR;
}
#endif

