單片機(jī)數(shù)字濾波算法如何實(shí)現(xiàn)?(附代碼)
關(guān)注、星標(biāo)公眾號(hào)
,
直達(dá)精彩內(nèi)容
ID:技術(shù)讓夢(mèng)想更偉大
整理:李肖遙
數(shù)字濾波無需其他的硬件成本,只用一個(gè)計(jì)算過程,可靠性高,不存在阻抗匹配問題。尤其是數(shù)字濾波可以對(duì)頻率很低的信號(hào)進(jìn)行濾波,這是模擬濾波器做不到的。
數(shù)字濾波使用軟件算法實(shí)現(xiàn),多輸入通道可共用一個(gè)濾波程序,降低系統(tǒng)開支。
只要適當(dāng)改變?yōu)V波器的濾波程序或運(yùn)算,就能方便地改變其濾波特性,這對(duì)于濾除低頻干擾和隨機(jī)信號(hào)會(huì)有較大的效果。
在單片機(jī)系統(tǒng)中常用的濾波算法有限幅濾波法、中值濾波法、算術(shù)平均濾波法、加權(quán)平均濾波法、滑動(dòng)平均濾波等。
限幅濾波算法
1#define A?
//允許的最大差值
2
3char data;?
//上一次的數(shù)據(jù)
4
5char?filter()
6
7{
8
9????
char
?datanew;?
//新數(shù)據(jù)變量
10
11????datanew=get_data();?
//獲得新數(shù)據(jù)變量
12
13????
if((datanew-
data)>A||(
data-datanew>A))
14
15????????
return?
data;
16
17????
else
18
19????????
return
?datanew;
20
21}
中值濾波算法
1
#define?N 11?//定義獲得的數(shù)據(jù)個(gè)數(shù)
2 3
char?filter()
4
5
{
6 7????
char value_buff[N];?
//定義存儲(chǔ)數(shù)據(jù)的數(shù)組
8 9????
char
?count,i,j,temp;
1011????
for
(count=
0
;count
1213????
{
1415????????
value_buf[count]=get_data();
1617????????
delay();?
//如果采集數(shù)據(jù)比較慢,那么就需要延時(shí)或中斷
1819????
}
2021????
for
(j=
0
;j
2223????
{
2425????????
if
(value_buff[i]>value_buff[i+
1
])
2627????????
{
2829????????????
temp=value_buff[i];
3031????????????
value_buff[i]=value_buff[i+
1
];
3233????????????
value_buff[i+
1
]=temp;
3435????????
}
3637????
}
3839
return value_buff[(N
-1
)/
2
];
4041
}
算術(shù)平均濾波算法
1
char?filter()
2
3{
4
5????
int?sum=
0;
6
7????
for(count=
0;count
8
9????{
10
11????????sum+=get_data();
12
13????????delay():
14
15????}
16
17????
return?(
char)(sum/N);
18
19}
加權(quán)平均濾波算法
1char?codej
q[N]={
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12};?
//code數(shù)組為加權(quán)系數(shù)表,存在程序存儲(chǔ)區(qū)
2
3char?codesum_jq=
1+
2+
3+
4+
5+
6+
7+
8+
9+
10+
11+
12;
4
5char?filter()
6
7{
8
9????char?count;
10
11????char?value_buff[N];
12
13????
int?sum=
0;
14
15????
for(count=
0;count
16
17????{
18
19????????value_buff[count]=get_data();
20
21????????delay();
22
23????}
24
25????
for(count=
0;count
26
27????????sum+=value_buff[count]*j
q[count];
28
29????
return (char)(sum/sum_jq);
30
31}
滑動(dòng)平均濾波算法
1
char?value_buff[N];
2
3
char?i=
0;
4
5
char?filter()
6
7{
8
9????
char?count;
10
11????
int?sum=
0;
12
13????value_buff[i++]=get_data();
14
15????
if(i==N)
16
17????????i=
0;
18
19????
for(count=
0;count
20
21????????sum=value_buff[count];
22
23????
return?(
char)(sum/N);
24
25}
低通濾波
1Yn=a*?Xn+(1-a)?*Yn-1
2
3式中?Xn——本次采樣值
4
5Yn-1——上次的濾波輸出值;
6
7a——濾波系數(shù),其值通常遠(yuǎn)小于1;
8
9Yn——本次濾波的輸出值。
1fL=a/2Pit?pi為圓周率3.14…
2
3式中?a——濾波系數(shù);
4
5t——采樣間隔時(shí)間;
6
7例如:當(dāng)t=0.5s(即每秒2次),a=1/32時(shí);
8
9fL=(1/32)/(2*3.14*0.5)=0.01Hz
往期好文合集
??最 后
??
?
免責(zé)聲明:本文內(nèi)容由21ic獲得授權(quán)后發(fā)布,版權(quán)歸原作者所有,本平臺(tái)僅提供信息存儲(chǔ)服務(wù)。文章僅代表作者個(gè)人觀點(diǎn),不代表本平臺(tái)立場(chǎng),如有問題,請(qǐng)聯(lián)系我們,謝謝!





