/*-------------------------------------------------------------------------
   AR168M demo external controller MCS51
   UART function copy right information

   Copyright (C) 2008. Lin, Rongrong <woody@palmmicro.com>

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   This software 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
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
-------------------------------------------------------------------------*/

#include "type.h"
#include "8051.h"
#include "sys.h"

#define UART_BUF_LEN	48

volatile DCHAR _iInputHead, _iInputTail;
volatile ICHAR _pInputBuf[UART_BUF_LEN];

void SerialInterrupt() interrupt 4 using 2
{
	DCHAR iVal;

	if (RI)
	{
		if (_iInputTail != _iInputHead)
		{
			_pInputBuf[_iInputHead] = SBUF;
			_iInputHead ++;
			if (_iInputHead == UART_BUF_LEN)
			{
				_iInputHead = 0;
			}
		}
		else
		{
			iVal = SBUF;	// drop it
		}
		RI = 0;
	}
}

void UART_SendChar(UCHAR iVal)
{
//	EA = 0;

	while (!TI);
	TI = 0;
	SBUF =  iVal;

//	EA = 1;
}

void UART_Init()
{
	_iInputHead = 0;
	_iInputTail = UART_BUF_LEN - 1;
}

void UART_Run()
{
	DCHAR iTail;

	iTail = _iInputTail + 1;
	if (iTail == UART_BUF_LEN)
	{
		iTail = 0;
	}

	while (iTail != _iInputHead)
	{
		UI_HandleSerialChar(_pInputBuf[iTail]);

		_iInputTail = iTail;
		iTail ++;
		if (iTail == UART_BUF_LEN)
		{
			iTail = 0;
		}
	}
}

