#include <p18f25k20.h>
#include <delays.h>
#include "main.h"
#include "AD.h"
uint24 ADBuffer[4];//AD数据缓冲区
uint24 ReadSPI(void)
{
uint8 i;
uint24 x = 0;
uint24 result = 0;
CS = 0;//启动转换
Delay10TCYx(2);//延时80us(时钟频率为1MHz)
CS = 1;//启动单次转换
Delay1KTCYx(20);;//延时80ms,等待转换完成
CS = 0;//进入休眠,准备读数据
Delay1TCY();//延时4us,等待数据就绪
if(SDO == 0)//判断数据是否就绪
{
for(i = 0;i < 24;i ++)
{
SCK = 0;
Delay1TCY();//延时4us,等待数据稳定
x = SDO;
while(SDO != x)//抖动处理,2次读出电平相同说明数据稳定
{
Delay1TCY();
x = SDO;
}
result <<= 1;
result |= x;
SCK = 1;
Delay1TCY();
}
}
CS = 1;//进入关断
Delay1TCY();
Delay1TCY();
Delay1TCY();
return result;
}
void ReadAD(void)
{
uint8 i;
for(i = 0;i < 4;i ++)
{
ADBuffer[i] = ReadSPI();//连续读4次AD转换结果
}
}
uint24 ADFilter(void)
{
uint8 i;
uint24 Max,Min;
uint24 Average = 0,Sum = 0;
Max = ADBuffer[0];
Min = ADBuffer[0];
for(i = 0;i < 4 ;i ++)
{
if(ADBuffer[i] > Max)
{
Max = ADBuffer[i]; //AD数据中的最大数据
}
if(ADBuffer[i] < Min)
{
Min = ADBuffer[i]; //AD数据中的最小数据
}
Sum += ADBuffer[i]; //读出的4个AD数据和
}
Average = (Sum - Max - Min) >> 1; //AD数据和去掉最大值和最小值,对剩下的2个数据求平均值
return Average; //返回滤波后的数据
}
|