/*=================================< Uart1.c >===============================*/
//   
//    Title:      UART1 UNIT
//    Saved date: 06 May 2003 10:12:01
//    Written by: JAG
//    Project:    RMS101 SBC
//    Target:     LH79520
//    Compiler:   GNU GCC for ARM
//		Copyright:	Subject to the Revely Open Source License (see readme.txt) 
//
// Simple non-interrupt UART Drivers for Uart Port 1.  This is the main serial
// port on the RMS101. Not using interrupts has limitations, but it does
// make the drivers easy to use, and almost foolproof when debugging code. 
// When the RMS101 is connected to a dumb terminal, these functions are a 
// very useful debugging mechanism.
//
// Note that some functions will not timeout.  Use with caution.
//
// History:
//	V1.00		17/07/02  Initial release.
//
/*============================================================================*/
 
#include <stddefs.h>
#include <regs.h> 
#include <uart1.h>  

/*-----------------------------< Variables >---------------------------*/

 
/*------------------------------< UartInit >---------------------------*/
void UartInit(BYTE bBaud)
{
	// Setup Port pins
	UARTMUX |= 0x000c;
	
	// Enable clock to Uart 1
	PERCLKCTRL &= 0xfffc;
	// Make sure internal clock source is selected
	PERCLKSEL &= 0xfffc;
	
	// Select Baud rate timing
	switch (bBaud)
	{
		case BAUD_115200:	UART1IBRD = 8;
								UART1FBRD = 0;
								break;
		case BAUD_9600:	UART1IBRD = 0x60;
								UART1FBRD = 0;
								break;
		default:				UART1IBRD = 0x60;
								UART1FBRD = 0;
								break;
	}
		
	UART1LCR_H = 0x70;  	// 8 data bits, no parity
	UART1CR = 0x0301;		// Enable UART to transmit and receive
}

/*----------------------------< UartDeInit >---------------------------*/
void UartDeInit(void)
{
	UART1CR = 0;
}


/*------------------------------< UartSend >---------------------------*/
void UartSend(char *string)
{
	while (*string != 0x00)
	{
		// Wait for space in Tx fifo
		while (UART1FR & 0x0020);
		// Load character
		UART1DR = *string++;
	}
}

/*----------------------------< UartSendChar >-------------------------*/
void UartSendChar(char c)
{
	// Wait for space in Tx fifo
	while (UART1FR & 0x0020);
	// Load character
	UART1DR = c;
}

/*------------------------------< UartGet >---------------------------*/
void UartGet(char *string, char MaxSize)
{
	char Data = 0, Num =0;
	
	
	// Wait for CR or Timeout (tbd)
	
	do 
	{
		while ((UART1FR) & 0x0010);	// Wait for character
		Data = (char)UART1DR;
		string[Num++] = Data;

	} while ((Data != 0x0d) && (Data != 10) && (Num < MaxSize));
	string[Num] = 0x00;	// add null
}
 

/*-----------------------------< UartGetKey >-------------------------*/
char UartGetKey(void)
{
	// Wait for character 
	while ((UART1FR) & 0x0010);
	
	return ((char)(UART1DR));
}

/*------------------------------< UartKey >---------------------------*/
char UartKey(void)
{
	if (UART1FR & 0x0010) 	// Check for Rx fifo empty
		return 0;
	else
		return 1;
}



