#include<ioavr.h>
#include "adcproc.h"
#include "utils.h"
#include "globdefs.h"

#define SKIP_SAMPLES 1//ADC采样时忽略样本数

#define BYTE unsigned char

#define ADC_MUX_I 0x00//MUX选择第0通道
#define ADC_MUX_U 0x01
#define ADC_MUX_T 0x02

BYTE fADCFlag = 0;
int iADCData = 0;

void InitADCSystem(void)
{
  PORTA_PORTA0 = PORTA_PORTA1 = PORTA_PORTA2 = 0; //内部上拉电阻无效,减少干扰
  DDRA_DDA0 = DDRA_DDA1 = DDRA_DDA2 = 0; //输入
  ADMUX_REFS1 = ADMUX_REFS0 = 1; //内部参考电压2.56V
  ADCSRA_ADATE = 0; //单次转换模式
  ADMUX_ADLAR = 0; //结果右对齐
}

void OpenADCSystem(void)
{
  ADCSRA_ADEN = 1; //允许ADC转换
  ADCSRA_ADIE = 1; //中断使能
}

void CloseADCSystem(void)
{
  ADCSRA_ADEN = 0;
  ADCSRA_ADIE = 0; //关闭ADC中断
}

void SetADCInput(TMEAS_CHAN channel)
{
  switch(channel)
  {
  case TMEAS_I_SENSE:
    ADMUX = ADMUX & 0xF0 | ADC_MUX_I; //ADMUX_MUX3=ADMUX_2=ADMUX_1=ADMUX_0=0;
    break;
  case TMEAS_U_SENSE:
    ADMUX = ADMUX & 0xF0 | ADC_MUX_U; //ADMUX_MUX3=ADMUX_2=ADMUX_1=0;ADMUX_0=1;
    break;
  case TMEAS_T_SENSE:
    ADMUX = ADMUX & 0xF0 | ADC_MUX_T; //ADMUX_MUX3=ADMUX_2=ADMUX_0=0;ADMUX_1=1;
    break;
  }
}

int ADCGetData(BYTE aver)
{
  int adccode = 0;
  BYTE repeats = (1 << aver) + SKIP_SAMPLES;
  BYTE i = 0;
  fADCFlag = 0;
  
  for(i = 0; i < repeats; i++)
  {
    ADCSRA_ADSC = 1; //开始转换
    while(!fADCFlag)//等待ADC中断
    {
      ;
    }
    if(i > (SKIP_SAMPLES - 1))
    {
      SREG_I = 0;//M8C_DisableGInt;
      adccode += iADCData;
      SREG_I = 1;//M8C_EnableGInt;
    }
    fADCFlag = 0;
  }
  
  adccode >>= aver;
  return (adccode);
}

#pragma vector=ADC_vect
__interrupt void ADCConverted(void)
{
  iADCData = ADC;
  fADCFlag = 1;
}

 

posted on 2015-01-08 01:36  ppStudio  阅读(347)  评论(0编辑  收藏  举报