#include <io.h>
#include <interrupt.h>
#include <sig-avr.h>

/****function prototype****/
/*Chip Initialize*/
void Chip_Init(void);

/*ADC get function*/
int AD_get(char ch);

/*in line assemble*/
#define nop() __asm__ __volatile__ ("nop")
#define sleep() __asm__ __volatile__ ("sleep")

int main(void)
{
	int ad_value;
	
	cli();		/* disable global interrupt */
	
	Chip_Init();
	
	sei();		/* enable global interrupt */
	
	ad_value = AD_get(0);	/* get ad value */
	
	while(1);
	
}

/**** interrupt function ****/
SIGNAL(SIG_ADC)
{
	return;		/*dummy*/
}

/**** sub functions ****/
/*AD conversion routine*/
int AD_get(char ch)
{
	/*set channel*/
	ch &= 0x07;
	outp(ch,ADMUX);
	
	/*start ad conversion*/
	cbi(ADCSR,ADIF);
	sleep();
	nop();
	nop();
	nop();
	return __inw(ADCL);	/*read ADCL first function from iomacros.h*/
}

void Chip_Init(void)
{
	/*enable sleep mode*/
	outp(BV(SE),MCUCR);
	
	/*for ADC*/
	outp(0,DDRA);	/*all input pins*/
	outp(0,PORTA);	/*disable pull up*/
	outp(BV(ADEN)|BV(ADSC)|BV(ADIE)|0x06,ADCSR);	/*clock 8MHz/64 = 125kHz*/
	sei();
	
	sleep();
/* recovering errata from ATMEL : When MPU exits from sleep mode, 2 or 3 instructions executed before entering interrupt functions. So some NOP instruction is recmmended to insert in codes. */
	nop();
	nop();
	nop();
	cli();
	
	return;
}
