adaptive.c
来自「adaptive filtering IIR and FIR」· C语言 代码 · 共 132 行
C
132 行
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* Decimal to Hex function */
void DecToHex(double *inPtr, int cnt){
double temp = 0;
double modd = 0;
short int hexval = 0;
short int jcnt;
FILE *hexoutput;
hexoutput= fopen("hexoutput.dat","w");
for(jcnt=0;jcnt<=cnt-1;jcnt++){
temp = *(inPtr + jcnt) * 32768;
modd = temp - floor(temp);
if(modd >= 0.5)
temp = ceil(temp);
else
temp = floor(temp);
hexval = (short int)temp;
fprintf(hexoutput,"%s"," .word 0x");
fprintf(hexoutput,"%X",hexval);
fprintf(hexoutput,"\n");
}
fcloseall();
return;
}
/* -------- MAIN -------- */
void main()
{
#define NL 32 /* length of FIR filter */
#define LEN 500
//long yn = 0; /* y(n), output from filter */
short int yn = 0;
short int outyn[LEN];
double xn[LEN];
short int xnbuf[NL];
short int w[NL];
int i,j,k,n;
//int mu = 338; /* 33(0.001); 338(0.01); 655(0.02) */
short int t = 0x028F;
short int mu_err;
short int dn = 0;
short int err;
short int err1[LEN];
double temp;
double modd;
int a; // A reg
FILE *yn_out; /* file pointer of y(n) */
FILE *w_out; /* file pointer of w(0) */
FILE *err_out; /* file pointer of e(n) */
yn_out = fopen("out_int.dat","w");/* open file for output y(n)*/
w_out = fopen("w_int.dat","w"); /* coefficient file */
err_out = fopen("err_int.dat","w");/* error signal file */
for(i=0;i<LEN+1;i++){
xn[i] = 0.25 * sin(2*i*3.141516/16);
}
for(k=0;k<NL;k++)
{ /* clear signal and coefficient buffers */
xnbuf[k]=0;
w[k] = 0;
}
for(n=0;n<LEN;n++)
{
// Clear sample buffer
for (i=NL-1;i>0;i--)
{
xnbuf[i]=xnbuf[i-1];
}
// Delay the sample buffer
xnbuf[0]=dn;
temp = (double)(xn[n] * 32768);
modd = temp - floor(temp);
if(modd >= 0.5)
temp = ceil(temp);
else
temp = floor(temp);
dn = (short int)temp; // dn = latest input
// FIR filtering
yn = 0;
for (j=0; j< NL; j++)
{
a = xnbuf[j] * w[j];
a <<= 1;
yn = yn + (short int)(a >> 16);
}
outyn[n] = yn;
err = dn-yn; //e(n) = d(n) - y(n)
err1[n] = err;
a = t * err;
a <<= 1;
mu_err = (short int)(a >> 16);
//update filter coeffificient
for (k=0; k< NL; k++)
{
a = mu_err * xnbuf[k];
a <<= 1;
w[k] = w[k] + (short int)(a >> 16);
}
fprintf(yn_out,"%f\n", (float)yn/32768 );
// fprintf(w_out,"%f\n", (float)w[n]/32768 );
fprintf(err_out,"%f\n",(float)err1[n]/32768 );
}
printf("Finish"); //complete filtering
fcloseall(); //close all opened files
// DecToHex(w,32);
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?