/* uart_polled.c - HCS12 UART (SCI) polled serial I/O driver implementation.
 * Copyright 2008 Colin D. Bennett <colin@gibibit.com>.
 *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *    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/>.
 *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *
 * This program uses polled asynchronous serial I/O on the HCS12 CPU. 
 * The HCS12 CPU has two SCI (UART) ports, SCI0 and SCI1.
 * We use SCI1 because SCI0 is reserved by DBug12. Connect to the connector 
 * P2 (the DB9 connector nearest to the power connector on the Dragon12-Plus
 * board) to use SCI1.
 *
 * The port baud rate and CPU frequency must be set (via UART_BAUD & F_CPU),
 * which is taken care of by the Makefile, via gcc '-D' options. We must
 * know the CPU clock frequency because the UART transmitter and receiver
 * run off of the same clock, divided by a certain value, which depends on
 * both the CPU clock rate and the baud rate. The actual calculation is done
 * in the hc12/setbaud.h utility header.
 *
 * Note: Be sure to disable hardware flow control (RTS/CTS) on your computer
 * when trying to communicate with the HCS12 CPU, since it is unsupported.
 */

#include "hc12drivers/uart_polled.h"
#include "hc12/hcs12.h"

void uart_init(void)
{
	/****** Configure SCI module. ******/

	/* Select baud rate. */
	/* The setbaud.h utility header takes in: F_CPU, UART_BAUD.
	 * It defines SCI1BDH and SCI1BDL for us based on calculations. */
#include "hc12/setbaud.h"    
	SCI1BDH = SCIBDH_VALUE;
	SCI1BDL = SCIBDL_VALUE;

	/* Configure word length, parity, and other configuration bits */
	SCI1CR1 = 0; /* no loopback mode, normal 8 data bits, no parity */

	/* Enable the transmitter and receiver. */
	SCI1CR2 = TE | RE;
}

void uart_putchar(char c)
{
	while (!(SCI1SR1 & TDRE))
		/* Wait for transmit data register to be empty. */;
	SCI1DRL = c;      /* Write to the SCI data register. */
}

char uart_getchar(void)
{
	while (!(SCI1SR1 & RDRF))
		/* Wait for receive data register full flag to be set. */;
	return SCI1DRL;   /* Read and return the SCI data register. */
}

