#define N 3
unsigned char p = 0; //队列指针
unsigned short buff[~((~0)<<N)+1] = {0}; //环形队列存储空间
unsigned short sum = 0; //初始和值
unsigned short aver = 0; //初始平均值
unsigned short ADresult; //保存AD采样结果
void TEST(void)
{
while(1)
{
getad(&ADresult); //取得本次采样结果
sum -= buff[p]; //本句及下句,替换环形队列以及和值中最早的一个值
sum += (buff[p]=ADresult);
aver = (sum + (1<<(N-1)))>>N; //移位代替除法求平均,整数运算,带四舍五入处理
p++; //队列指针移动
p &= (unsigned char)(~((~0)<<N)); //只保留变量p的低N位,保证指针越界后能“环回”到0
}
} |