/******************************************************************************
*
* Copyright 2006-2015 Freescale Semiconductor, Inc.
* Copyright 2016-2017 NXP
*
******************************************************************************/

/****************************************************************************//*!
*
* @file     adc.c
*
* @brief    ADC routines
*
*******************************************************************************/

/*******************************************************************************
* Includes
*******************************************************************************/
#include "device_registers.h"
#include "main.h"
#include "adc.h"
#include "power_mode.h"

/*****************************************************************************
*
* Function: void ADC0_Init(uint32_t sampleTime, adcAvgSel_t avgSel)
*
* Description: Init ADC0
*
* Note: sampleTime value in range from 2 to 256
*
*****************************************************************************/
void ADC0_Init(uint32_t sampleTime, uint32_t avgSel, uint8_t mode)
{
    switch (mode)
    {
    	case (RUN_PLL):
		{
    	    // ADC input clock selected in PCC, System Clock PLL (SCGPCLK), 80MHz
    	    // Should be max 64MHz, divide by 2
    	    // ADC input clock = 80/2 = 40MHz, tclk = 25ns
    	    // 12bit resolution, ADCK division by 1, no internal alternate clocks but only selectable via PCC
    	    ADC0->CFG1 = 0x00000004;
    	    // set sample time, 11 - 1 = 10, 10 x 18ns = 0.18us
    	    ADC0->CFG2 = sampleTime;
    	    // software trigger, no compare, no DMA, default VREFH/L
    	    ADC0->SC2 = 0x00000000;

    		break;
		}
    	case (RUN_FIRC):
		{
    	    // ADC input clock selected in PCC, FIRC 48MHz
    	    // Should be max 64MHz, divide by 1
    	    // ADC input clock = 48/1 = 48MHz, tclk = 21ns
    	    // 12bit resolution, ADCK division by 1, no internal alternate clocks but only selectable via PCC
    	    ADC0->CFG1 = 0x00000004;
    	    // set sample time, 11 - 1 = 10, 10 x 18ns = 0.18us
    	    //ADC0->CFG2 = sampleTime;
    	    ADC0->CFG2 = 2;
    	    // software trigger, no compare, no DMA, default VREFH/L
    	    ADC0->SC2 = 0x00000000;

    		break;
		}
    	case (VLPR):
		{
    	    // ADC input clock selected in PCC, SIRCDIV2, 8MHz
    	    // Should be max 64MHz, divide by 1
    	    // ADC input clock = 8/2 = 4MHz, tclk = 250ns
    	    // 12bit resolution, ADCK division by 1, no internal alternate clocks but only selectable via PCC
    	    ADC0->CFG1 = 0x00000004;
    	    // set sample time, 11 - 1 = 10, 10 x 18ns = 0.18us
    	    ADC0->CFG2 = sampleTime;
    	    // software trigger, no compare, no DMA, default VREFH/L
    	    ADC0->SC2 = 0x00000000;

    		break;
		}
    }
}
