#include <avr/io.h>
#include "PVR.h"

void main(void)
{
	xmegaInit();							//setup XMega
	delayInit();							//setup delay functions
	ServoCInit();							//setup PORTC Servos
	ServoDInit();							//setup PORTD Servos
	ADCAInit();								//setup PORTA analong readings
	lcdInit();								//setup LCD on PORTK
	lcdString("PVR Code Demo");				//display "PVR Code Demo" on top line (Line 0) of LCD
	lcdGoto(1,0);							//move LCD cursor to the second line (Line 1) of LCD
	lcdString("IMDL Fall 2010");			//display "IMDL Fall 2010" on second line
	PORTQ_DIR |= 0x01;						//set Q0 (LED) as output
	PORTH_DIR = 0xFF;						//set Port H as all output
	PORTJ_DIR = 0b11111110;					//set PORTJ bit 0 to input, 1-7 to output
	
	int value, value2, mainloopcount = 0;	//Value to be used for A/D
	
	while(1){								//Main Demo Loop

/***************************/
//Set Data Direction Register
//Read Pin 0 on Port J
//Set pin value to Pin 1 on Port J
/***************************/
	PORTJ_DIR = 0b11111110;
	if ((PORTJ_IN & 0b00000001) == 0b00000001)
		PORTJ_OUT &= 0b11111101;
	else
		PORTJ_OUT |= 0b00000010;


/***************************/
//Set Data Direction Register
//Read Pin 0 on Port J
//Set pin value to Pin 1 on Port J
/***************************/

	value = ADCA0(); 			//Read A/D value from PortA, Pin0 (between 0-4096)
	value = (value-2000)/10;	//Scale value to between -200 and 200
	ServoC0(value);				//Move Servo to position based on 'value'

	value2 = ADCA1(); 			//Read A/D value from PortA, Pin0 (between 0-4096)
	value2 = (value2-2000)/10;	//Scale value to between -200 and 200
	ServoD0(value2);			//Move Servo to position based on 'value'


/***************************/
//Set Port H to Random Value
//Random() fucntion returns random number between 0 and 32677
/***************************/

	PORTH_OUT = random();						

/***************************/
//Output data from this iteration to the LCD
/***************************/

	if (mainloopcount > 50){	//update LCD every ~50 loops
		lcdData(0x01);			//Clear LCD
		lcdString("ADC0: ");
		lcdInt(value);
		lcdGoto(1,0);
		lcdString("ADC1: ");
		lcdInt(value2);
		mainloopcount=0;
	}
	mainloopcount++;
}

}
