/**************************************************************************************************
---------------------------------------------------------------------------------------------------
	Copyright (c) 2004-2007, Jonathan Bagg
	All rights reserved.

	 Redistribution and use in source and binary forms, with or without modification, are permitted 
	 provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of 
	  conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of 
	  conditions and the following disclaimer in the documentation and/or other materials provided 
	  with the distribution.
    * Neither the name of Jonathan Bagg nor the names of its contributors may be used to 
	  endorse or promote products derived from this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR 
  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 
  AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 
  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 
  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
  POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------------------------------
   Project name : Infidigm AVR Drivers
   Processor	: Any AVR with a UART or USART
   Compiler		: WinAVR (GCC 4.1.2)
   File name    : uart.c
---------------------------------------------------------------------------------------------------
   Modifications: 

   Revision 1.0  2004/06/17 	Bagg
   - Cleaned up for release
   
   Revision 2.0  2007/09/29 	Bagg
   - added broad support of avr micros
   - added disabling of printing types
   - added print_hex()
   - added rx buffer & functions to read it
   - added "string mode" --> allows pointers to strings to be placed on the tx buffer instead of
		of the ascii characters.
   - added selection between UARTs 0,1,2 and 3 on parts that have them available
   - added optional HOLD THREAD y/n feature
   - added function to read the space left on the TX buffer
   - added the ability to have a tx buffer that is greater than 128 bytes
   - changed global interrupt en/disable in txbyte() to en/disable TX interrupt only
   - added support for lower buad rates by setting up UBRRH
   
---------------------------------------------------------------------------------------------------
	Release Notes:
	
	Processor/Family	Compiles for	Tested		Notes

	attiny2313				Yes				No
	atmega8					Yes				No
	atmega48/88/168			Yes				Yes
	atmega649				Yes				No
	atmega169				Yes				No
	at90pwm2/3				Yes				No
	at90usb1286/1287		Yes				No		only uart 1
	atmega64/128			Yes				Yes
	at90can32/64/128		Yes				Yes
	atmega1281/2561			Yes				Yes
	atmega1280/2560			Yes				No
	
	Size: 356 to 1374 bytes depending on options selected
   
---------------------------------------------------------------------------------------------------
   Created      : 20 Jan 2004     	           Author(s) : Jonathan Bagg
---------------------------------------------------------------------------------------------------
   UART Interrupt driver with HyperTerminal Display I/O functions
---------------------------------------------------------------------------------------------------
**************************************************************************************************/

#include <avr/io.h> 
#include <avr/interrupt.h>
#include "uart.h"

/**************************************************************************************************
*   INTERNAL GLOBAL VARIABLES
**************************************************************************************************/
static volatile TXTYPE tx_used;					//Used size of the Used TX Buffer
static unsigned char txDone;					//tx activity flag
static unsigned char txBuff[TXSIZE];			//Transmit Buffer
static unsigned char rxbuff[RXSIZE];			//Receive Buffer
static unsigned char rx_on;						//position to put data on the RX buffer
static unsigned char rx_off;					//position to take data off the RX buffer
static unsigned char rx_used;					//Used size of the Used RX Buffer
#if STRING_MODE == 1
	static TXTYPE tx_on;						//position to put data on the TX buffer
	#if LARGE_STRING == 1
	static unsigned int rom_ctr;				//position of the next byte to TX in the current
	#elif LARGE_STRING == 0						//|-> string (string mode only)
	static unsigned char rom_ctr;
	#endif
static unsigned char tx_type[TXSIZE/8];			//'array of bits' - each bit represents if the
#endif											//|-> corresponding byte in the tx buffer is data 
												//|-> or a pointer to a string in ROM

/**************************************************************************************************
*   start_UART(); - See 'uart.h' Header file for Description
**************************************************************************************************/
void start_UART(void)
{
 UR_H = (char)((int)UART_BAUD_SELECT >> 8);
 UR_L = (char)UART_BAUD_SELECT;
 UR_A = 0x00;
 UR_B = _BV(RX_INT_EN)|_BV(TX_INT_EN)|_BV(RX_EN)|_BV(TX_EN);		//enable Rx, TX, Rx IQR, & Tx IRQ
}

/**************************************************************************************************
*   UART_PrintfProgStr(); - See 'uart.h' Header file for Description
**************************************************************************************************/
#ifdef USE_ROM_STRING
void UART_PrintfProgStr(const char* pBuf) 
{
#if STRING_MODE == 0
 while (pgm_read_byte_near(pBuf)!=0) {
   	txbyte(pgm_read_byte_near(pBuf));
   	pBuf++;
 }
 #elif STRING_MODE == 1
 #if HOLD_THREAD == 1
 unsigned char done=1;
 while(done) {
	if(tx_used < TXSIZE-1)
		done = 0;
 }
 #elif HOLD_THREAD == 0
 if (tx_used >= TXSIZE-1)
	return;
 #endif 
 UR_B&= ~_BV(TX_INT_EN);					//disable TX Interrupt
 if(!txDone) {								//finished txing
 	rom_ctr = 1;
	txDone = 1;
	UDR = pgm_read_byte_near(pBuf);			//re-start interrupts
 }
 txBuff [(tx_on & (TXSIZE-1))] = ((int)pBuf >> 8);
 write_tx_type(tx_on, 1);
 tx_on++;
 txBuff [(tx_on & (TXSIZE-1))] = ((int)pBuf & 0xFF);
 tx_on++;
 tx_used+=2;
 UR_B|= _BV(TX_INT_EN);						//re-enable TX Interrupt
 #endif
}
#endif

/**************************************************************************************************
*   prints16(); - See 'uart.h' Header file for Description
**************************************************************************************************/
#ifdef USE_SIGNED_INT
void prints16(unsigned int x)
{
 if (x>0x8000) {
 	txbyte ('-');
 	x^=0xFFFF;
 	x++;
 }
 txbyte(x / 10000 + 0x30);					//Add ASCI offset for digits (0-9)-> 0x30
 x=x % 10000;
 txbyte(x / 1000 + 0x30);
 x=x % 1000;
 txbyte(x / 100 + 0x30);
 x=x % 100;
 txbyte(x / 10 + 0x30);
 x=x%10;
 txbyte(x + 0x30);
}
#endif

/**************************************************************************************************
*   printu16(); - See 'uart.h' Header file for Description
**************************************************************************************************/
#ifdef USE_UNSIGNED_INT
void printu16(unsigned int x)
{
 txbyte(x / 10000 + 0x30);					//Add ASCI offset for digits (0-9)-> 0x30
 x=x % 10000;
 txbyte(x / 1000 + 0x30);
 x=x % 1000;
 txbyte(x / 100 + 0x30);
 x=x % 100;
 txbyte(x / 10 + 0x30);
 x=x%10;
 txbyte(x + 0x30);
}
#endif 

/**************************************************************************************************
*   print_hex(); - See 'uart.h' Header file for Description
**************************************************************************************************/
#ifdef USE_HEX
void print_hex(unsigned char x)
{
 unsigned char done, y;
 
 //txbyte('0');
 //txbyte('x');
 done = 2;
 y = (x & 0x0F);
 x>>=4;
 while (done) {
	if (x < 0x0A) {
		txbyte(x + 0x30);
	}
	else {
		txbyte(x + 0x37);
	}
	done--;
	x = y;
 }
}
#endif

/**************************************************************************************************
*   txbyte(); - See 'uart.h' Header file for Description
**************************************************************************************************/
void txbyte(char data) 
{
 #if STRING_MODE == 0
 static TXTYPE tx_on;
 #endif
 #if HOLD_THREAD == 1
 unsigned char done=1;
 while(done) {
	if(tx_used < TXSIZE) 
		done = 0;
 }
 #elif HOLD_THREAD == 0
 if (tx_used >= TXSIZE-1)
	return;
 #endif 
 UR_B&= ~_BV(TX_INT_EN);			//disable TX Interrupt
 if(!txDone) {						//finished txing
 	txDone = 1;
	UDR = data;						//re-start interrupts
 }
 else {
	txBuff [(tx_on & (TXSIZE-1))] = data;
	#if STRING_MODE == 1
	write_tx_type(tx_on, 0);
	#endif
	tx_on++;
	tx_used++;
 }
 UR_B|= _BV(TX_INT_EN);				//re-enable TX Interrupt
}

/**************************************************************************************************
*   read_tx_buff_space(); - See 'uart.h' Header file for Description
**************************************************************************************************/
TXTYPE read_tx_buff_space(void)
{
 return (TXSIZE - tx_used);
}

/**************************************************************************************************
*   UART0 TX ISR - See 'uart.h' Header file for Description
**************************************************************************************************/
SIGNAL(DSIG_UART_TX_ISR)
{
 static TXTYPE tx_off;
 if(tx_used) {
	#if STRING_MODE == 1
	unsigned char wrote=0;
	while(!wrote) {
		if (read_tx_type(tx_off)) {
			unsigned int temp;
			temp = (txBuff[(tx_off & (TXSIZE-1))] << 8) | txBuff[((tx_off+1) & (TXSIZE-1))];
			temp+= rom_ctr;
			if (pgm_read_byte_near(temp)!=0) {
				UDR = pgm_read_byte_near(temp);
				wrote = 1;
				rom_ctr++;
			}
			else {
				rom_ctr = 0;
				tx_off+=2;
				tx_used-=2;
				if (!tx_used) {
					wrote = 1;
					txDone = 0;
				}
			}
		}
		else {
			UDR = txBuff[(tx_off & (TXSIZE-1))];
			wrote = 1;
			tx_off++;
			tx_used--;
		}
	}
	#elif STRING_MODE == 0
	UDR = txBuff[(tx_off & (TXSIZE-1))];
	tx_off++;
	tx_used--;
	#endif
 }
 else txDone = 0;
}

/**************************************************************************************************
*   UART RX New Character Received ISR - See 'uart.h' Header file for Description
**************************************************************************************************/
SIGNAL(DSIG_UART_RX_ISR)
{
 if (rx_used < RXSIZE) {					//protect buffer if it fills up
	rx_on++;
	rx_used++;
 }
 rxbuff[(rx_on & (RXSIZE-1))] = UDR;
}

/**************************************************************************************************
*   scan(); - See 'uart.h' Header file for Description
**************************************************************************************************/
#ifdef USE_INT_SCAN
signed int scan(char indata) 
{
 unsigned int value=0;
 static unsigned char pos,neg,i,data[5]; 
 
 if (indata == RESET_SCAN) {
	i = 0;
	pos = 0;
	neg = 0;
	data[0] = 0;							//Clear Array 
	data[1] = 0; 
	data[2] = 0; 
	data[3] = 0; 
	data[4] = 0; 
 }
 else {
	if (indata == ENTER) {				//loop until ENTER is pressed 
		while (pos > 0) {
			value *= 10;				//Build U16 number from ASCII array
			value += data[i++];
			pos--;
		}
		if (neg) 
			value*= -1;
	} 
	if (indata== BACKSPACE) {			//backspace action
		if (!pos && neg) {
 			neg = 0;
 			txbyte(BACKSPACE);
 			txbyte(0x20);
 			txbyte(BACKSPACE);
 		}
		if (pos!=0) {
			pos--;
			data[pos] = 0;
			txbyte(BACKSPACE);
			txbyte(0x20);
			txbyte(BACKSPACE);
		}
	}
	else {								//fill array with numbers only until full
		if (pos<5 && indata>=0x30 && indata<=0x39) {
			data[pos] = indata - 0x30;
			pos++;
			txbyte(indata);				//Print key just pressed 
		}
		if (!pos && !neg && indata=='-') {
 			neg = 1;
 			txbyte(indata);
 		}
	}
 }
 return (value); 
} 
#endif


/**************************************************************************************************
*   read_tx_type(); - See 'uart.h' Header file for Description
**************************************************************************************************/
#if STRING_MODE == 1
unsigned char read_tx_type(TXTYPE address)
{
 unsigned char remdr, j, value;
 
 address&= TXSIZE-1;
 remdr = address % 8;
 value = 1;
 for (j=0;j<remdr;j++) {
	value = value << 1;
 }
 return (tx_type[address/8] & value);
}
#endif

/**************************************************************************************************
*   write_tx_type(); - See 'uart.h' Header file for Description
**************************************************************************************************/
#if STRING_MODE == 1
void write_tx_type(TXTYPE address, unsigned char type)
{
 unsigned char remdr, j, value;
 
 address&= TXSIZE-1;
 remdr = address % 8;
 value = 1;
 for (j=0;j<remdr;j++) {
	value = value << 1;
 }
 if (type) 
	tx_type[address/8] |= value;
 else
	tx_type[address/8] &= ~value;
}
#endif

/**************************************************************************************************
*   new_uart_rx(); - See 'uart.h' Header file for Description
**************************************************************************************************/
unsigned char new_uart_rx(void)
{
 unsigned char status;
 
 if (rx_on != rx_off)
	status = 1;
 else
	status = 0;
 return status;
}

/**************************************************************************************************
*   read_uart_rx(); - See 'uart.h' Header file for Description
**************************************************************************************************/
unsigned char read_uart_rx(void)
{
 if (rx_on != rx_off) {
	rx_off++;
	rx_used--;
 }
 return(rxbuff[(rx_off & (RXSIZE-1))]);
}
