#include "AD7921.h"
void AD7921_select_convert_channel(unsigned short channel)
{
unsigned char i=16;
unsigned short data=channel;
AD7921_CS_H;
AD7921_SCLK_H;
AD7921_CS_L;
while(i--)
{
AD7921_SCLK_H; //SCLK=1
if(data&0x8000)
AD7921_DIN_H; //下降沿之前建立时间5ns
else
AD7921_DIN_L;
AD7921_SCLK_L; //下降沿有效
data<<=1; //下降沿之后保持时间6ns
}
AD7921_SCLK_H; //SCLK=1
asm("nop");
AD7921_CS_H;
}
/******************************************************************************
读AD7921的数据
*****************************************************************************/
unsigned short AD7921_ReadData(void)
{
unsigned char i=16;
unsigned short data=0x0000;
AD7921_CS_H;
AD7921_SCLK_H;
AD7921_CS_L;
while(i--) //
{
AD7921_SCLK_H; //SCLK=1
delay_1us();
data<<=1;
AD7921_SCLK_L; //下降沿有效
if(AD7921_DOUT) data++;//读AD值
}
AD7921_SCLK_H; //SCLK=1
data&=0x0fff;
AD7921_CS_H;
return data;
}
/***********************************************************************
获取接收的值
每个点采15次数据,去掉最小和最大的各5个,把中间的5个做平均
***********************************************************************/
unsigned short AD7921_Average(unsigned short channel)
{
unsigned char i=0,j=0;
unsigned short data[15],temp=0,sum=0;
for(i=0;i<15;i++)
{
AD7921_select_convert_channel(channel);
data=AD7921_ReadData();
}
for(i=0;i<14;i++)
for(j=i+1;j<15;j++)
{
if(data>data[j])
{
temp=data;
data=data[j];
data[j]=temp;
}
}
for(i=5;i<10;i++)
sum+=data;
sum/=5;
return sum;
}
unsigned char Read_Voltage(float *v,unsigned short channel)
{
unsigned short average;
average=AD7921_Average(channel);
if((average<2312)||(average>3687))
return 0;
else
{
*v=3.281*average/4096;
return 1;
}
}