#include <startup.h>
#include <LPC214X.h>
#include <armVIC.h>
#include <type.h>
#include <irq.h>
#include <TFT018.h>
#include <rprintf.h>

// LED P0.31
#define LED 0x80000000
#define	INT_VECT_NUM	0

void IRQ_ADC(void) __attribute__ ((interrupt("IRQ")));

int times = 0;
volatile char ADC_DONE = 0;
unsigned int ADC_Data = 0;

void IRQ_ADC (void){
	if ((IOSET0 & LED) == 0)
		IOSET0 = LED;
	else
		IOCLR0 = LED;
	
	times++;
	ADC_Data = AD0GDR;		// read ADC
	ADC_DONE = 1;
	VICVectAddr = 0x00;
	}

/*----------------------------------------------------------*\
 | ADC Initial                                              |
\*----------------------------------------------------------*/
void  ADCInit(void) {
	PINSEL1 |= 1 << 24;		// P0.28 -> AD0.1
	}

char s[20], *sp;
int input_str(int ch){
	*sp ++ = (char)ch;
	*sp = 0;
	return ch;
}

int main (void) {
	Initialize();
	BacklightOn();
	LCD_Init();
	LCD_Clear_Screen(Blue);

	IODIR0  |= LED;
	ADCInit();

	// set up EXTINT interrupt
	VICIntSelect &= ~(1<<ADC0_INT);
	VICIntEnable |= (1<<ADC0_INT);

	(*(&VICVectCntl0+INT_VECT_NUM)) = 0x20 | ADC0_INT; // choose highest priority ISR slot 	
	(*(&VICVectAddr0+INT_VECT_NUM)) = (int)IRQ_ADC;
	
	enableIRQ();

	/* ADC setting */
	AD0CR = (1 << 1)						|	// SEL=8,ch1
			((12000000 / 1000000 - 1) << 8)	|	// CLKDIV=Fpclk/1000000-1,1MHz
			(0 << 16)						|	// BURST=0, software control
			(0 << 17)						|	// CLKS=0, 11clock
			(1 << 21)						|  	// PDN=1, normal mode
			(0 << 22)						|  	// TEST1:0=00, normal mode
			(1 << 24)						|	// START=1,start ADC
			(0 << 27);

	for(;;) {
		char s[20];
		if( ADC_DONE ) {
			sp = s;
			rprintf_devopen( input_str );
			rprintf("ADC :%d",times);
			LCD_PutString(1,30,s,0xF800,0xFFE0);
			ADC_DONE = 0;

			ADC_Data = (ADC_Data >> 6) & 0x3ff;
			ADC_Data = ADC_Data * 3300;			// ref 3.3v 
			ADC_Data = ADC_Data / 1024;
			sp = s;
			rprintf_devopen( input_str );
			rprintf("%04d mV", ADC_Data);
			LCD_PutString(1,60,s,0xF800,0xFFE0);

			AD0CR |= 1 << 24;					// start again
			}
		}
	}
