Previous Page
    /******************************************************************************
    * ADC.c
    *
    * Description: This source file allows the Kinetis K02 to use the on chip ADCs
    *              with a 5MHz sample rate and hardware averaging of 32 samples for
    *              every conversion.
    *
    * Controller: Kinetis MK02F12810
    *
    * Spencer Black April 5, 2015
    *******************************************************************************
    * Master Include File
    ******************************************************************************/
    #include "includes.h"

    /******************************************************************************
    * ADC Defines
    ******************************************************************************/
    #define DISABLEMODULE 0x1F    //Value to disable ADC module
    #define DIVIDE        0x6     //Value to divide down the clock by 8 (5MHz)
    #define AVGSELECT     0x3     //Value for Hardware averaging (32 samples)

    /******************************************************************************
    * Public Function prototypes
    ******************************************************************************/
    void ADC_Init(void);
    INT16U ADC_Value(INT8U ADC);

    /******************************************************************************
    * ADC_Init(void)
    *
    * Description: Sets up the ADCs on the Kinetis K02 for minimum sample rate of
    *              5MHz, single ended 8-bit with hardware averaging (32 samples).
    *              DOES NOT TURN THE ADCs ON.
    *
    * Parameters: None
    ******************************************************************************/
    void ADC_Init(void){
        SIM_SCGC6  |= SIM_SCGC6_ADC0_MASK;         //Initialize ADC Clock
        ADC0_SC1A   = ADC_SC1_ADCH(DISABLEMODULE); //Disable before configuration
        ADC0_CFG1   = ADC_CFG1_ADIV(DIVIDE);   //Set sample rate 5MHz (bus clock/8)

        //hardware averaging (32 samples per return value)
        ADC0_SC3    = (ADC_SC3_AVGE_MASK | ADC_SC3_AVGS(AVGSELECT));
    }

    /******************************************************************************
    * INT16U ADC_Value(INT8U ADC)
    *
    * Description: Enables user specified ADC and returns the value from the
    *              conversion in the return register.
    *
    * Parameters: ADC is the value of the ADC to initialize on the MCU
    *             ReturnVal is the value of the return register
    ******************************************************************************/
    INT16U ADC_Value(INT8U ADC){
        const INT8U ADCVal = ADC;
        static INT8U ReturnVal = 0;

        ADC0_SC1A = ADCVal;                     //Start sample of ADC
        while(!(ADC0_SC1A & ADC_SC1_COCO_MASK));//Wait for Conversion Complete Flag
        ReturnVal = ADC0_RA;                    //Store return register value
        return ReturnVal;
    }
    

Previous Page