/*------------------------------------------------------- 
 * AD変換
 * 16F18313, 16F18323, 16F18324, 16F18344, 
 * 16F18325, 16F18345, 16F18326, 16F18346, 
 * 16F18854, 16F18855, 16F18856, 16F18857, 
 * 16F18875, 16F18876, 16F18877
 *-------------------------------------------------------*/
#include <xc.h>
#include <stdint.h>
#include "mcr.h"
#include "adc.h"

#if   defined(_16F18313) || defined(_16F18323) || \
      defined(_16F18324) || defined(_16F18344) || \
      defined(_16F18325) || defined(_16F18345) || \
      defined(_16F18326) || defined(_16F18346) 

/* ADCモジュール初期化 */
void ADC_Init(void)
{
  ADCON0bits.ADON   = 1; /* Enabled */
  ADCON1bits.ADFM   = 1; /* Right Justified Format */
  ADCON1bits.ADCS   = 2; /* FOSC/32 */
  ADCON1bits.ADNREF = 0; /* VSS */
  ADCON1bits.ADPREF = 0; /* VDD */
}

/* ADC実行 */
adc_val_t ADC_Read(adc_ch_t ch)
{
  ADCON0bits.CHS = ch;
  ADCON0bits.ADON = 1;
  __delay_us(5); 
  ADCON0bits.GO_nDONE = 1;
  while (ADCON0bits.GO_nDONE != 0) {
    ;
  }
  return ((adc_val_t)ADRESH << 8) | (adc_val_t)ADRESL;
}

#elif defined(_16F18854) || defined(_16F18855) || \
      defined(_16F18856) || defined(_16F18857) || \
      defined(_16F18875) || defined(_16F18876) || \
      defined(_16F18877) 

/* ADCモジュール初期化 */
void ADC_Init(void)
{
  ADCON0bits.ADON   = 1; /* ADC Enabled */
  ADCON0bits.ADFRM0 = 1; /* Right Justified Format */
  ADCON1 = 0x00;
  ADCON2 = 0x00;
  ADCON3 = 0x00;
  ADCLK  = 0x0F; /* FOSC/32 */
  ADREF  = 0x00; /* ADNREF=VSS, ADPREF=VDD */
}

/* ADC実行 */
adc_val_t ADC_Read(adc_ch_t ch)
{
  ADPCH = ch;      
  ADCON0bits.ADON   = 1;
  ADCON0bits.ADCONT = 0; 
  __delay_us(5); 
  ADCON0bits.ADGO = 1;
  while (ADCON0bits.ADGO != 0) {
    ;
  }
  return ((adc_val_t)ADRESH << 8) | (adc_val_t)ADRESL;
}

#else

# error "YOUR DEVICE IS NOT SUPPORTED"

#endif
