/* 
 * Copyright (C) 2004 Darren Hutchinson (dbh@gbdt.com.au)
 * 
 * This software is a derivitive of a the Atmel bootstrap contained in
 * application note AVR109 and is only to be used under the copyright
 * restrictions of that program.
 *
 * This notice may not be removed from this source code module.
 *
 * Contact Atmel via email at avr@atmel.com for commercial use.
 *
 * $Id: serial.c,v 1.3 2004/04/22 06:27:19 dbh Exp $
 */

#include <inttypes.h>
#include <avr/io.h>

#include "serial.h"

/* serialInit() initializes the serial port used for the 
 * serial guider input.
 *
 * Passed:
 *         Nothing
 *
 * Returns:
 *         Nothing.
 */
void
initbootuart(void)
{
    // Set serial rate
    UBRR0H = (CLK_RATE / BAUD_RATE / 16 - 1) >> 8;
    UBRR0L = (CLK_RATE / BAUD_RATE / 16 - 1) & 0xff;

    /* Setup registers
     * 8 bits, no parity, RX enable, TX enable. Only the Rx interrupts are
     * enabled at this point.
     */
    UCSR0B = 0;            // Disable all interrupts
    UCSR0C = _BV(URSEL0) | _BV(UCSZ01) | _BV(UCSZ00);
    UCSR0B = _BV(RXEN0) | _BV(TXEN0);
}

/* sendchar() sends a single character
 *
 * Passed
 *      ch      The character to send
 *
 * Returns
 *      Nothing
 */
void
sendchar(char ch)
{
    while (! (UCSR0A & _BV(UDRE0)))
        ;

    UDR0 = ch;
}

/* rxCheck() checks to see if a serial character has been received
 *
 * Passed
 *      nothing
 * Returns
 *      0               No character to receive
 *      non-zero        Character to receive
 */
char
rxCheck(void)
{
    return UCSR0A & _BV(RXC0);
}

/* recchar() waits for a character to be received and returns it
 *
 * Passed
 *      Nothin
 *
 * Returns
 *      The character received
 */
unsigned char
recchar(void)
{
    while ( ! (UCSR0A & _BV(RXC0)))
        ;

    return UDR0;
}
