#include   "FunctionState.h"
#include   "plib_port.h"         
#include "plib_adc1.h"  
extern uint16 adc[2] ;
uint8 Fuction_State = 1 ;
uint8 Control_SDZ = 1 ;
uint16 LD_AD_Val;


void FunctionState_Task(void)
{
        static uint16 Into_A_count = 0;
        
        static uint16 Into_B_count = 0;
        
        static uint16 Into_C_count = 0;
        
        static uint8_t adcResetFlag = 0;

        adcResetFlag = !adcResetFlag;
        if (adcResetFlag == 0)
        {
            ADC1_Initialize();
            ADC1_Enable();
            ADC1_ChannelSelect(ADC_POSINPUT_AIN6, ADC_NEGINPUT_GND);
            ADC1_ConversionStart();
            return;
        }
        
        
        
        
        LD_AD_Val = adc[1];
        
        switch(Fuction_State)
        {
            case Function_State_A:
            Into_A_count = 0;
             //if((adc[0]>649 && adc[0]<874) || (adc[0]>1777 && adc[0]<2003)) //A switch to B    
             if((adc[0]>581 && adc[0]<862) || (adc[0]>1788 && adc[0]<2014))
             {
                  Into_B_count++;
                 if(Into_B_count >= 400) //4000ms
                {
                  Fuction_State = Function_State_B;
                }
             }
             else if(adc[0]<581 || adc[0]>2014) //A switch to C   
             {
                  Into_C_count++;
                 if(Into_C_count >= 100) //1000ms
                {
                  Fuction_State = Function_State_C;
                }
             }
            break;
            

            case Function_State_B:
             Into_B_count = 0;
             if(adc[0]>897&&adc[0]<1754) //B switch to A    
             {
                  Into_A_count++;
                  
                  
                 if(Into_A_count >= 50) //500ms
                {
                  Fuction_State = Function_State_A;
                }
             }
             else if(adc[0]<581 || adc[0]>2014) //B switch to C   
             {
                  Into_C_count++;
                 if(Into_C_count >= 100) //1000ms
                {
                  Fuction_State = Function_State_C;
                }
             }
            break;


            case Function_State_C:
            Into_C_count = 0;
             if((adc[0]>614 && adc[0]<897) || (adc[0]>1754 && adc[0]<1979)) //C switch to B    
             {
                  Into_B_count++;
                 if(Into_B_count >= 400) //4000ms
                {
                  Fuction_State = Function_State_B;
                }
             }
             //else if(adc[0]>931&&adc[0]<1721) //C switch to A    
             else if(adc[0]>897&&adc[0]<1754) //8.25->7.95  15.25->15.55  
             {
                  Into_A_count++;
                 
                 if(Into_A_count >= 50) //500ms
                {
                  Fuction_State = Function_State_A;
                }
             }
            break;

            default:
				break;

        }
              
}
