#include "startup/lpc2xxx.h"
#include "startup/config.h"
#include "adc.h"
#include "timer.h"


#define CRYSTAL_FREQUENCY FOSC
#define PLL_FACTOR        PLL_MUL
#define VPBDIV_FACTOR     PBSD


uint16 getAnalogueInput0(uint8 channel) {
  uint16 returnResult;

  //start conversion now (for selected channel)
  //(24th bit stats conversation now)
  AD0CR = (AD0CR & 0xFFFFFF00) | (1 << channel) | (1 << 24);

  //wait till done
  while((AD0DR & 0x80000000) == 0) ;

  //get result and adjust to 10-bit integer
  returnResult = (AD0DR>>6) & 0x3FF;

  
  return returnResult;
}

uint16 getAnalogueInput1(uint8 channel) {
	uint16 returnResult;


	//start conversion now (for selected channel)
	//(24th bit stats conversation now)
	AD1CR = (AD1CR & 0xFFFFFF00) | (1 << channel) | (1 << 24);
	
	//wait till done
	while((AD1DR & 0x80000000) == 0);

	//get result and adjust to 10-bit integer
	returnResult = (AD1DR>>6) & 0x3FF;

	return returnResult;
}

/*****************************************************************************
 *
 * Description:
 *
 ****************************************************************************/
void
initAdc(void)
{
	volatile uint32 integerResult;

 //Set pinsel for P0.21 to work as AIN1.6
    PINSEL1 &= ~0x00000800;
    PINSEL1 |=  0x00000800;

    //Set pinsel for P0.22 to work as AIN1.7
    PINSEL1 &= ~0x00001000;
    PINSEL1 |=  0x00001000;

    //Set pinsel for P0.30 to work as AIN0.3
    PINSEL1 &= ~0x10000000;
    PINSEL1 |=  0x10000000;

  //initialize ADC0
  AD0CR = (1 << 0)                      |    //SEL = 1, dummy channel #0
         ((CRYSTAL_FREQUENCY *
           PLL_FACTOR /
		   VPBDIV_FACTOR) / 4500000 - 1) << 8
						|  //set clock division factor, so ADC clock is 4.5MHz
		 (0 << 16)                 |  //BURST = 0, conversions are SW controlled
		 (0 << 17)                 |  //CLKS  = 0, 11 clocks = 10-bit result
		 (1 << 21)                 |  //PDN   = 1, ADC is active
		 (1 << 24)                 |  //START = 1, start a conversion now
		 (0 << 27);		              //EDGE  = 0, not relevant when start=1

  //short delay and dummy read
  zegarek(10000);
  integerResult = AD0DR;
  
    //initialize ADC0
  AD1CR = (1 << 0)                             |  //SEL = 1, dummy channel #0
         ((CRYSTAL_FREQUENCY *
           PLL_FACTOR /
		   VPBDIV_FACTOR) / 4500000 - 1) << 8 |
							//set clock division factor, so ADC clock is 4.5MHz
		 (0 << 16)                 |  //BURST = 0, conversions are SW controlled
		 (0 << 17)                 |  //CLKS  = 0, 11 clocks = 10-bit result
		 (1 << 21)                 |  //PDN   = 1, ADC is active
		 (1 << 24)                 |  //START = 1, start a conversion now
		 (0 << 27);					  //EDGE  = 0, not relevant when start=1

  //short delay and dummy read
  zegarek(10000);
  integerResult = AD1DR;
}

