int main(void)
{
     
    /* Clock initialization */
    SystemInit();

    /* test system initialization */
    test_Init();
        //adi_gpio_OutputEnable(EN_5V, true);
        //adi_gpio_SetHigh(EN_5V);
        
    do 
    {
      if(ADI_PWR_SUCCESS != adi_pwr_Init())
        {
          DEBUG_MESSAGE("Failed to intialize the power service\n");
          break;
        }
      
      if(ADI_PWR_SUCCESS != adi_pwr_SetLFClockMux(ADI_CLOCK_MUX_LFCLK_LFXTAL))
      {
        return(eResult);
      }
      
      if(ADI_PWR_SUCCESS != adi_pwr_EnableClockSource(ADI_CLOCK_SOURCE_HFXTAL, true))
      {
        return(eResult);
      }

      if(ADI_PWR_SUCCESS != adi_pwr_SetRootClockMux(ADI_CLOCK_MUX_ROOT_HFXTAL))
      {
        return(eResult);
      }

      
      if(ADI_PWR_SUCCESS != adi_pwr_EnableClockSource(ADI_CLOCK_SOURCE_LFXTAL,true))
      {
        return(eResult);
      }
   
      if (ADI_PWR_SUCCESS != adi_pwr_SetClockDivider(ADI_CLOCK_HCLK,1))
      {
          DEBUG_MESSAGE("Failed to intialize the power service\n");
      }
      if (ADI_PWR_SUCCESS != adi_pwr_SetClockDivider(ADI_CLOCK_PCLK,1))
      {
          DEBUG_MESSAGE("Failed to intialize the power service\n");
      }

  
      if(ADI_RTC_SUCCESS !=rtc_Init())
        {
          DEBUG_MESSAGE("\nFailed to initialize RTC device \n");
        }
      

      
      if(ADI_GPIO_SUCCESS != adi_gpio_Init(gpioMemory, ADI_GPIO_MEMORY_SIZE))
        {
            DEBUG_MESSAGE("adi_gpio_Init failed\n");
            break;
        }
      //P0.13 --> LED3
      adi_gpio_OutputEnable(LED3, true);
      //P1.12 --> LED4 
      adi_gpio_OutputEnable(LED4, true);
      adi_gpio_OutputEnable(CO_HEATER, true);
      adi_gpio_OutputEnable(CO_SENSE, true);
      adi_gpio_OutputEnable(PM25_LED, true);
      adi_gpio_OutputEnable(PM25_FAN, true);
      adi_gpio_OutputEnable(DBG_ST8_PIN, true);
      adi_gpio_OutputEnable(DBG_ADC_PIN, true);

      adi_gpio_SetLow(CO_HEATER);
      adi_gpio_SetLow(CO_SENSE);
      adi_gpio_SetLow(PM25_LED);
      adi_gpio_SetLow(PM25_FAN);
      adi_gpio_SetLow(DBG_ADC_PIN);   
      adi_gpio_SetHigh(LED3);
      adi_gpio_SetHigh(LED4);
      
      ADC_Setup();
      
      adi_tmr_Open(TIMER_DEVICE_1,aDeviceMemory1,ADI_TMR_MEMORY_SIZE,&hDevice1); 
      adi_tmr_RegisterCallback( hDevice1, GPTimer1Callback ,hDevice1);
      
      adi_tmr_SetPrescaler(hDevice1, ADI_GPT_PRESCALER_256);
      adi_tmr_SetLoadValue( hDevice1, GPT1_LOAD_1SEC);
     
      DEBUG_MESSAGE("AQ Sensor initializing!\n");    
        
    }while(0);
    
    do
    {}
    while(1);
    
    
 
}
int main(void)
{
     
    /* Clock initialization */
    SystemInit();

    /* test system initialization */
    test_Init();
        //adi_gpio_OutputEnable(EN_5V, true);
        //adi_gpio_SetHigh(EN_5V);
    
  /*    SWITCHED TO LOW POWER MODE - ACTIVE MODE    */
  pwrResult = adi_pwr_EnterLowPowerMode(ADI_PWR_MODE_ACTIVE,NULL,0x00);  //Low Power Active mode
  DEBUG_RESULT("\n Failed to enter active mode %04d",pwrResult,ADI_PWR_SUCCESS);
  /*    BUCK CONVERTER ENABLED TO REDUCE POWER      */
  adi_pwr_EnableHPBuck(true); 
  
  NUM_FAN_500MS_CYCLES = fanOnTime/0.5;//Number of 500ms cycles equals ratio of given fanOnTime to 0.5 
  
    do 
    {
      if(ADI_PWR_SUCCESS != adi_pwr_Init())
        {
          DEBUG_MESSAGE("Failed to intialize the power service\n");
          break;
        }
      
      if(ADI_PWR_SUCCESS != adi_pwr_SetLFClockMux(ADI_CLOCK_MUX_LFCLK_LFXTAL))
      {
        return(eResult);
      }
      
      if(ADI_PWR_SUCCESS != adi_pwr_EnableClockSource(ADI_CLOCK_SOURCE_HFXTAL, true))
      {
        return(eResult);
      }

      if(ADI_PWR_SUCCESS != adi_pwr_SetRootClockMux(ADI_CLOCK_MUX_ROOT_HFXTAL))
      {
        return(eResult);
      }

      
      if(ADI_PWR_SUCCESS != adi_pwr_EnableClockSource(ADI_CLOCK_SOURCE_LFXTAL,true))
      {
        return(eResult);
      }
   
      if (ADI_PWR_SUCCESS != adi_pwr_SetClockDivider(ADI_CLOCK_HCLK,1))
      {
          DEBUG_MESSAGE("Failed to intialize the power service\n");
      }
      if (ADI_PWR_SUCCESS != adi_pwr_SetClockDivider(ADI_CLOCK_PCLK,1))
      {
          DEBUG_MESSAGE("Failed to intialize the power service\n");
      }

  
      if(ADI_RTC_SUCCESS !=rtc_Init())
        {
          DEBUG_MESSAGE("\nFailed to initialize RTC device \n");
        }
      

      
      if(ADI_GPIO_SUCCESS != adi_gpio_Init(gpioMemory, ADI_GPIO_MEMORY_SIZE))
        {
            DEBUG_MESSAGE("adi_gpio_Init failed\n");
            break;
        }
      //P0.13 --> LED3
      adi_gpio_OutputEnable(LED3, true);
      //P1.12 --> LED4 
      adi_gpio_OutputEnable(LED4, true);
      adi_gpio_OutputEnable(CO_HEATER, true);
      adi_gpio_OutputEnable(CO_SENSE, true);
      adi_gpio_OutputEnable(PM25_LED, true);
      adi_gpio_OutputEnable(PM25_FAN, true);
      adi_gpio_OutputEnable(DBG_ST8_PIN, true);
      adi_gpio_OutputEnable(DBG_ADC_PIN, true);

      adi_gpio_SetLow(CO_HEATER);
      adi_gpio_SetLow(CO_SENSE);
      adi_gpio_SetLow(PM25_LED);
      adi_gpio_SetLow(PM25_FAN);
      adi_gpio_SetLow(DBG_ADC_PIN);   
      adi_gpio_SetHigh(LED3);
      adi_gpio_SetHigh(LED4);
      
      ADC_Setup();
      
      adi_tmr_Open(TIMER_DEVICE_1,aDeviceMemory1,ADI_TMR_MEMORY_SIZE,&hDevice1); 
      adi_tmr_RegisterCallback( hDevice1, GPTimer1Callback ,hDevice1);
      
      adi_tmr_SetPrescaler(hDevice1, ADI_GPT_PRESCALER_256);
      adi_tmr_SetLoadValue( hDevice1, GPT1_LOAD_1SEC);
     
      DEBUG_MESSAGE("AQ Sensor initializing!\n");    
        
    }while(0);
    
    do
    {}
    while(1);
    
    
 
}
int main(void) {
    ADI_AFE_DEV_HANDLE  hDevice;
    int16_t             dft_results[DFT_RESULTS_COUNT];
    q15_t               dft_results_q15[DFT_RESULTS_COUNT];
    q31_t               dft_results_q31[DFT_RESULTS_COUNT];
    q31_t               magnitude[DFT_RESULTS_COUNT / 2];
    q15_t               phase[DFT_RESULTS_COUNT / 2];
    fixed32_t           magnitude_result[DFT_RESULTS_COUNT / 2 - 1];
    fixed32_t           phase_result[DFT_RESULTS_COUNT / 2 - 1];
    char                msg[MSG_MAXLEN];
    uint32_t            offset_code;
    uint32_t            gain_code;
    uint32_t            rtiaAndGain;

    /* Initialize system */
    SystemInit();

    /* Change the system clock source to HFXTAL and change clock frequency to 16MHz     */
    /* Requirement for AFE (ACLK)                                                       */
    if (ADI_SYS_SUCCESS != SystemTransitionClocks(ADI_SYS_CLOCK_TRIGGER_MEASUREMENT_ON))
    {
        FAIL("SystemTransitionClocks");
    }
    
    /* SPLL with 32MHz used, need to divide by 2 */
    SetSystemClockDivider(ADI_SYS_CLOCK_UART, 2);
    
    /* Test initialization */
    test_Init();

    /* Initialize static pinmuxing */
    adi_initpinmux();

    /* Initialize the UART for transferring measurement data out */
    if (ADI_UART_SUCCESS != uart_Init())
    {
        FAIL("uart_Init");
    }

    /* Initialize the AFE API */
    if (ADI_AFE_SUCCESS != adi_AFE_Init(&hDevice)) 
    {
        FAIL("Init");
    }

    /* Set RCAL and RTIA values */
    if (ADI_AFE_SUCCESS != adi_AFE_SetRcal(hDevice, RCAL)) 
    {
        FAIL("adi_AFE_SetRcal");
    }
    if (ADI_AFE_SUCCESS != adi_AFE_SetRtia(hDevice, RTIA)) 
    {
        FAIL("adi_AFE_SetTia");
    }

    /* AFE power up */
    if (ADI_AFE_SUCCESS != adi_AFE_PowerUp(hDevice)) 
    {
        FAIL("adi_AFE_PowerUp");
    }

    /* Delay to ensure Vbias is stable */
    delay(2000000);                                                             

    /* Temp Channel Calibration */
    if (ADI_AFE_SUCCESS != adi_AFE_TempSensChanCal(hDevice)) 
    {
        FAIL("adi_AFE_TempSensChanCal");
    }
    
    /* Auxiliary Channel Calibration */
    if (ADI_AFE_SUCCESS != adi_AFE_AuxChanCal(hDevice)) 
    {
        FAIL("adi_AFE_AuxChanCal");
    }    

    /* Excitation Channel Power-Up */
    if (ADI_AFE_SUCCESS != adi_AFE_ExciteChanPowerUp(hDevice)) 
    {
        FAIL("adi_AFE_ExciteChanPowerUp");
    }

    /* TempCal results will be used to set the TIA calibration registers. These */
    /* values will ensure the ratio between current and voltage is exactly 1.5  */
    if (ADI_AFE_SUCCESS != adi_AFE_ReadCalibrationRegister(hDevice, ADI_AFE_CAL_REG_ADC_GAIN_TEMP_SENS, &gain_code))
    {
        FAIL("adi_AFE_ReadCalibrationRegister, gain");
    }
    if (ADI_AFE_SUCCESS != adi_AFE_WriteCalibrationRegister(hDevice, ADI_AFE_CAL_REG_ADC_GAIN_TIA, gain_code))
    {
        FAIL("adi_AFE_WriteCalibrationRegister, gain");
    }
    if (ADI_AFE_SUCCESS != adi_AFE_ReadCalibrationRegister(hDevice, ADI_AFE_CAL_REG_ADC_OFFSET_TEMP_SENS, &offset_code))
    {
        FAIL("adi_AFE_ReadCalibrationRegister, offset");
    }
    if (ADI_AFE_SUCCESS != adi_AFE_WriteCalibrationRegister(hDevice, ADI_AFE_CAL_REG_ADC_OFFSET_TIA, offset_code))
    {
        FAIL("adi_AFE_WriteCalibrationRegister, offset");
    }

    /* Update FCW in the sequence */
    seq_afe_acmeasBioZ_4wire[3] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_FCW, FCW);
    /* Update sine amplitude in the sequence */
    seq_afe_acmeasBioZ_4wire[4] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_AMPLITUDE, SINE_AMPLITUDE);
      
    /* Recalculate CRC in software for the AC measurement, because we changed   */
    /* FCW and sine amplitude settings.                                         */
    adi_AFE_EnableSoftwareCRC(hDevice, true);
    while(true)
    {
      
      /* Perform the Impedance measurement */
      if (ADI_AFE_SUCCESS != adi_AFE_RunSequence(hDevice, seq_afe_acmeasBioZ_4wire, (uint16_t *)dft_results, DFT_RESULTS_COUNT)) 
      {
          FAIL("Impedance Measurement");
      }   

      /* Print DFT complex results to console */     
      PRINT("DFT results (real, imaginary):\r\n");
      sprintf(msg, "    CURRENT     = (%6d, %6d)\r\n", dft_results[0], dft_results[1]);
      PRINT(msg);
      sprintf(msg, "    VOLTAGE     = (%6d, %6d)\r\n", dft_results[2], dft_results[3]);
      PRINT(msg);       

      /* Convert DFT results to 1.15 and 1.31 formats.  */
      convert_dft_results(dft_results, dft_results_q15, dft_results_q31);

      /* Magnitude calculation */
      /* Use CMSIS function */
      arm_cmplx_mag_q31(dft_results_q31, magnitude, DFT_RESULTS_COUNT / 2);

      /* Calculate final magnitude value, calibrated with RTIA the gain of the instrumenation amplifier */
      rtiaAndGain = (uint32_t)((RTIA * 1.5) / INST_AMP_GAIN);
      magnitude_result[0] = calculate_magnitude(magnitude[1], magnitude[0], rtiaAndGain);

      /* Phase calculations */
      if (magnitude_result[0].full)
      {
          /* Current phase    */
          phase[0] = arctan(dft_results[1], dft_results[0]);
          /* Voltage phase    */
          phase[1] = arctan(dft_results[3], dft_results[2]);
          /* Impedance phase  */
          phase_result[0] = calculate_phase(phase[0], phase[1]);
      }
      /* No need to calculate the phase if magnitude is 0 (open circuit) */
      else 
      {
          /* Current phase    */
          phase[0]                = 0;
          /* Voltage phase    */
          phase[1]                = 0;
          /* Impedance phase  */
          phase_result[0].full    = 0;
      }

      /* Print final results to console */
      PRINT("Final results (magnitude, phase):\r\n");
      print_MagnitudePhase("Impedance", magnitude_result[0], phase_result[0]);
      
      //sprintf_fixed32(tmp, magnitude);
      
 
    }
    /* Restore to using default CRC stored with the sequence */
    adi_AFE_EnableSoftwareCRC(hDevice, false); 

    /* AFE Power Down */
    if (ADI_AFE_SUCCESS != adi_AFE_PowerDown(hDevice)) 
    {
        FAIL("PowerDown");
    }

    /* Uninitialize the AFE API */
    if (ADI_AFE_SUCCESS != adi_AFE_UnInit(hDevice)) 
    {
        FAIL("Uninit");
    }
    
    /* Uninitilize the UART */
    uart_UnInit();

    PASS();

}