#include "math.h"
#include <stdio.h>
#include <stdlib.h>
int Arg_Tan(int R,int X);
void Filter_DFT(short SmpRate,short *smpdata,int *rms,int *ang);
// DFT滤波举例
void DFT_Sample()
{
short i=0;
short smp[80]; // 采样值缓冲(80点)
int rms; // 有效值
int ang; // 相位
for(i=0;i<80;i++)
{
smp[i] = cos(2*3.1415926*i/80)*1.41421*10000;
}
//有效值和相位的结果扩大了65536
Filter_DFT(80,smp,&rms,&ang);
}
/******************************************************************
Function name:
Author: rxb
Version: V1.00计算
Date: 2008-5-12
Description: DFT
Input Parameter:
Return Parameter: int
Modify History:
<Author> <Date> <Modification>
rxb 2008-05-12 首次版本创建
*******************************************************************/
void Filter_DFT(short SmpRate,short *smpdata,int *rms,int *ang)
{
static short DFT_XS[1024];
static short First_Run=0;
float fdata,fr,fx;
short i;
int R,X,data;
// 滤波系数初始化化(放大1024*512)
if(First_Run != 0xa5)
{
First_Run = 0xa5;
for(i=0;((i<SmpRate)&&(DFT_XS!=0));i++)
{
fr = sin(2.0*3.14159265*(float)i/SmpRate)* (0.7071067812*(2.0/SmpRate)*1024);
fx = cos(2.0*3.14159265*(float)i/SmpRate)* (0.7071067812*(2.0/SmpRate)*1024);
//SmpRate=80(max= 9268)
DFT_XS[i*2+0]=(short)(fr*512);
DFT_XS[i*2+1]=(short)(fx*512);
}
}
if(!smpdata) return;
for(i=0,R=0,X=0;i<SmpRate;i++)
{
data = ((int)(smpdata[i]))*DFT_XS[i*2+0];
R += (data>>3);
data = ((int)(smpdata[i]))*DFT_XS[i*2+1];
X += (data>>3);
}
fdata = ((float)R)*R+((float)X)*X;
*rms = (int)sqrt(fdata);
*ang = Arg_Tan(R,X);
}
/******************************************************************
Function name:
Author: rxb
Version: V1.00
Date: 2008-5-12
Description: 反正切计算
Input Parameter:
Return Parameter: int
Modify History:
<Author> <Date> <Modification>
rxb 2008-05-12 首次版本创建
*******************************************************************/
#define TANSTEP 8 /* 1/8度 */
#define TANSIZE TANSTEP*90
int Arg_Tan(int R,int X)
{
static int TanTab[TANSIZE];
static int TanB=0;
static int arg,ur,ux;
static short begin,end,mid;
static float fArg;
/***************/
/* 初时化TAB表 */
/***************/
if(TanB==0)
{
TanB =0xff;
for(begin=0;begin<TANSIZE;begin++)
{
fArg=2.0*3.1415926/(360.0*TANSTEP)*begin; /* 步长0.125度 */
fArg=tan(fArg);
TanTab[begin]=(int)(fArg*1024.0);
}
}
/*******************/
/* 差表计算Arg_Tan */
/*******************/
if(R<0) ur = 0 - R;
else ur = R;
if(X<0) ux = 0 - X;
else ux = X;
while((ur>0x200000)||(ux>0x200000))
{
ur>>=1;ux>>=1;
}
if(ur==0)
{
if(X>0) return ( 90*65536);
else return (-90*65536);
}
arg = ux*1024/ur;
begin = 0;
end = TANSIZE-1;
while(begin<=end)
{
mid=(begin+end)>>1;
if(arg>TanTab[mid])
{
if(arg<=TanTab[mid+1]) break;
begin = mid+1; /* 向右找 */
}
else
{
if(arg>=TanTab[mid-1]) break;
end = mid-1; /* 向左找 */
}
}
/*插值*/
arg = ((int)mid)*(65536/TANSTEP);
if ((R<=0)&&(X>=0)) arg=(180*65536-arg); /* 2象限 */
else if((R<=0)&&(X<=0)) arg=(arg-180*65536); /* 3象限 */
else if((R>=0)&&(X<=0)) arg=(0-arg); /* 4象限 */
return(arg);
}