#include "common.h"
#include "f35x_adc.h"

void f35x_adc_init(){
  
  // Enable Vref and ADC
  ADC0MD |= 0x80; // AD0EN => 1
  
  // 5.1.1 Vref select
  //ADC0CF &= ~(0x04); // AD0VREF => 0 (default)
  // 5.1.2 Input Buffers
  //ADC0BUF = 0; // bypass (default)
  ADC0BUF = 0xAA; // use buffer (both + and - are connected upper buffer)
  // 5.1.3 Moduler Clock
  ADC0CLK = div_round(SYSCLK, 2.4576E6) - 1;
  // 5.1.4 Decimation Ratio
  //ADC0DEC = 0x0017; // Decimation: (23 + 1) = 24
  ADC0DEC = 39;
  
  //ADC0CN |= 0x10; // AD0POL => 1, Bipolar (default)
  ADC0CN |= 0x03; // PGA gain => 8
  
  // 5.2 Calibration
  ADC0MD |= 0x01; // AD0SM[2:0] => 0b001, Internal full calibration
  //ADC0CF &= ~(0x10); // AD0ISEL => 0, SINC3 interrupt (default)
  
  while(ADC0STA & 0x40); // wait while AD0CBSY = 1 
  
  // Enable Interrupt
  EIE1 |= 0x08; // EADC0 => 1
}
