//usarttest.c
//
//Program to communicate with 8251A USART
//
//Derek Marston and Peter Susi
//4/18/03

#include "common.h"
#include "iob32.h" //all IO and memory names

//	Authorize interrupts.

#define cli()	_asm("andcc #$EF")

#define TDRE	0x80	/* transmit ready bit */

void main(void)
{

//load stack pointer...can be done in linker file
for (;;)
{
	ConfigPorts();
	ConfigUSART();
}

//	ConfigSCI();
//	cli();

//	for (;;)
//	{}		//infinite loop
	
}

//Configure Direction Registers
void ConfigPorts()
{
	DDRA = 0x0F;
	/*
	pin 0 = USART reset
	pin 1 = Read'
	pin 2 = Write'
	pin 3 = command/data'
	pin 4 = TxRDY
	pin 5 = RxRDY

	*/

	DDRB = 0xFF; //PORTB is command/status/data register of USART
	//set to output to initialize USART

}

/*Configure 8251 USART for:
;		Asyncronous serial data
;		Baud Rate Factor = 16
;		8Bit data, no parity
;		1 stop bit
;		Enable transmitter
*/
void ConfigUSART()
{
	PORTB = 0x4E; //send initialization code to USART

	PORTA = 0x07; //set pin 0 high for USART hardware reset

	wait();

	PORTA = 0x06; //end reset pulse

	PORTA = 0x0E; //set USART ready for COMMAND
	PORTA = 0x0A; //Set USART ready for WRITE 
	PORTA = 0x0E; //end write pulse

	wait();

	PORTB = 0x05; //send second byte of initialization code

	PORTA = 0x0E; //set USART ready for COMMAND
	PORTA = 0x0A; //Set USART ready for WRITE 
	PORTA = 0x0E; //end write pulse

	wait();

	PORTA = 0x06; //set USART to idle mode
}



//Configures port for Asynchronous serial 8-bit data, no parity, 1 stop bit
//enable the transmitter and receiver
void ConfigSCI()
{
	
	SC0CR1 = 0x00; 	
 		// enable Tx, Rx and RxInterrupt

	SC0CR2 = 0x2C;

	SC0BDL = 0x34;	//BR divisor for 9600 BPS

}

//Waits for the transmitter to be ready (until TDRE bit in the Status Register is 1)
//then writes the contents of the passed parameter (one byte) to the Data Register
void CharOut(BIT_CHAR tosend)
{
	while (!(SC0SR1 & TDRE))  //TDRE is defined above
	{}	

	SC0DRL = tosend.byte;
}	

// Reads last byte from the Data register and returns it.

BIT_CHAR GetKey()
{
	BIT_CHAR temp;
	temp.byte = SC0DRL;
	return temp;
}


// Interrupt Routine for recieving Hyperterminal bytes
//

@interrupt void _SCIRx_ISR(void)
{
          SC0SR1; // read Status Reg to clear interrupt 	

	  SC0DRL = SC0DRL;    // Echo back byte
/*
	*ptecr++ = SC0DRL;		// get the char 
	if (ptecr >= &buffer[SIZE])	// put it in buffer
		ptecr = buffer;
*/


}


@interrupt void _IRQ_ISR(void)
{
	// generate square wave on interrupt

	DDRA = 0xFF;
	
	for(;;) //generate a square wave on all pins of Port A
	{
		PORTA = 0x0;		//turn all bits off
		wait();

		PORTA = 0xFF;		//turn all bits on
		wait();
	}	


}

void wait(void)
{
	int count;
	for (count = 0; count < 4; count++)
	{}
}
