#include "adc.h"
#include "dwarfcore.h"
#include "cpld.h"
long int val;
long int temp;

void initAdc(void)
{
	
	P6SEL=0xff;	//disable I/O on all port 6 pins (see note on ADC port pg17-5 in users manual)
	P6DIR=0;	//Set all port 6 pins to be inputs
	
	//set ADC control register 0
	ADC12CTL1=SHP+ADC12SSEL_3+CONSEQ_1; //use SMCLK as source, pulse mode sampling, sequence of conversions mode
	ADC12MCTL0=SREF_1+INCH_0;
	ADC12MCTL1=SREF_1+INCH_1;
	ADC12MCTL2=SREF_1+INCH_2;
	ADC12MCTL3=SREF_1+INCH_3;
	ADC12MCTL4=SREF_1+INCH_4;
	ADC12MCTL5=SREF_1+INCH_5; 
	ADC12MCTL6=SREF_1+INCH_6;
	ADC12MCTL7=SREF_1+INCH_7+EOS;
	ADC12IE = 0x80;  //enable adcisr only on last conversion       
	ADC12CTL0=SHT0_15+SHT1_15+MSC+REF2_5V+REFON+ADC12ON+ENC; //ADC config 
	
 	 
}


void adcIsr(MotorChannel* mc,RotaryValve* rv,Heater* h)
//called (like all ISRs!) with interrupts DISABLED
//so, we must enable them for cases where we don't return in < 40 microseconds
{
 
  if (ADC12IV == 20)  //this IV for memory register 7 prog for ADC ch 7
  {  //sequence completed - process data
       //first read all data as fast as possible so that int can be reenabled
      uint16 mtr0 = ADC12MEM0;
      uint16 mtr1 = ADC12MEM1;
      uint16 ADC3 = ADC12MEM3;
      uint16 ADC7;
        
        if(mc[1].flags & pressureSenseSwitch) mc[1].inPressure=ADC12MEM4;
	 	else mc[1].outPressure=ADC12MEM4;

	 	if(h->tempSenseSwitch==1) h->tempSense1=ADC12MEM5;
	 	 else h->tempSense2=ADC12MEM5;
 	h->thermoCouple=ADC12MEM6;
                
        ADC7 = ADC12MEM7;  ///this is the last conversion, and clears the ifg
 
    //all data read and ready to renable int
    _EINT();
    
    if (!TBCCR1)  //derive signed current from PWM output
      mc[0].motorCurrent = 0;
    else if (DCORMOTOROUT & DCOR0DIR)
      mc[0].motorCurrent = -mtr0;
    else
      mc[0].motorCurrent = mtr0;

    if (!TBCCR2)
      mc[1].motorCurrent = 0;
    else if (DCORMOTOROUT & DCOR1DIR)
      mc[1].motorCurrent = -mtr1;
    else
      mc[1].motorCurrent = mtr1;

    if (mtr0 > mc[0].maxCurrent)
	  MotorOverCurrent(&mc[0]);

    if (mtr1 > mc[1].maxCurrent )
          MotorOverCurrent(&mc[1]);
    
    if(mc[1].flags & pressureSenseSwitch)
	  {
	   _DINT();	   
 	   mc[0].inPressure=mc[1].inPressure;
 	   sensorImage|= DCORPRESSL|DCORPRESEN;
 	   updateSensorImage();
 	   mc[1].flags &= ~pressureSenseSwitch;
 	  }
    else
      {
	  _DINT();
	  mc[0].outPressure=mc[1].outPressure;
  	  sensorImage&=~(DCORPRESSL);
  	  sensorImage|= DCORPRESEN;
      updateSensorImage();
	  mc[1].flags |= pressureSenseSwitch;
 	  }

 	if(h->tempSenseSwitch==1)
 	{
     _DINT();
     h->tempSenseSwitch=0;
 	 sensorImage|= (DCORTEMPSL | DCORTEMPEN );
     updateSensorImage();	
 	 }
     else
 	 {
      _DINT();
     h->tempSenseSwitch=1;
 	 sensorImage|= DCORTEMPEN;
 	 sensorImage&= ~DCORTEMPSL;
     updateSensorImage();
 	 }
 }	 
}
