1775 views|0 replies

2015

Posts

0

Resources
The OP
 

The algorithm of digital filtering in single chip microcomputer [Copy link]

The main function of a single-chip microcomputer is to control peripheral devices and realize certain communications and data processing. However, in certain specific occasions, mathematical operations are inevitably used, although single-chip microcomputers are not good at implementing algorithms and performing complex operations. The following mainly introduces how to use single-chip microcomputers to realize digital filtering.

When the single-chip microcomputer collects data, random errors will be encountered. Random errors are caused by random interference. Their characteristics are that when measuring the same quantity under the same conditions, its size and sign will change irregularly and cannot be predicted, but the results of multiple measurements conform to statistical laws. In order to overcome the errors caused by random interference, filtering technology can be used in hardware, and software algorithms can be used to implement digital filtering in software. Filtering algorithms are often an important part of the system measurement and control algorithm, and they are very real-time.

Using digital filtering algorithms to overcome random interference errors has the following advantages:

1. Digital filtering does not require additional hardware costs, only uses one calculation process, has high reliability, and does not have impedance matching problems. In particular, digital filtering can filter very low frequency signals, which analog filters cannot do.

2. Digital filtering is implemented using software algorithms. Multiple input channels can share one filtering program, reducing system expenses.

3. As long as the filtering procedure or operation of the filter is appropriately changed, its filtering characteristics can be easily changed, which will have a greater effect on filtering out low-frequency interference and random signals.

4. The commonly used filtering algorithms in the single-chip microcomputer system include limited amplitude filtering, median filtering, arithmetic mean filtering, weighted average filtering, sliding average filtering, etc.

(1) Limiting filter algorithm

During this operation, two adjacent samples are subtracted to find their increment, and then the absolute value of the increment is compared with the maximum difference A allowed between the two samples. The size of A depends on the specific situation of the object being measured. If it is less than or equal to the maximum difference allowed, the current sampling is valid; otherwise, the last sampling value is taken as the sample of this data.

The program code of the algorithm is as follows:

01 #define A // Maximum allowed difference
02 char data; // Last data
03 char filter()
04 {
05 char datanew; // New data variable
06 datanew=get_data(); // Get new data variable
07 if( (datanew-data)>A||(data-datanew>A) )
08 return data;
09 else
10 return datanew;
11 }
Note: The limit filter method is mainly used to process data that changes slowly, such as temperature, position of an object, etc. When using it, the key is to select a suitable gate limit A. Usually this can be obtained from empirical data, and can be obtained through experiments when necessary.

(2) Median filter algorithm

The operation process is to sample a certain parameter N times continuously (N is generally an odd number), then arrange the values of the N samples from small to large, and then take the middle value as the sampling value this time. The whole process is actually a sequence sorting process.

The program code of the algorithm is as follows:

01 #define N 11 //Define the number of data obtained02
char filter()
03 {
04 char value_buff[N]; //Define an array to store data05
char count,i,j,temp;
06 for(count=0;count<N;count++) //Get data07
{
08 value_buf[count]=get_data();
09 delay(); //If the data collection is slow, then a delay or interrupt is required10
}
11
12 for(j=0;j<N-1;j++) //Sort data using the bubble method. Of course, it is best to use other sorting methods{ for(value_buff>value_buff[i+1]
13 {
14 temp=value_buff;
15 value_buff=value_buff[i+1];
16 value_buff[i+1]=temp;
17 }
18 }
19 return value_buff[(N-1)/2];
20 }
Description: Median filtering is more suitable for removing fluctuations caused by accidental factors and pulsation interference caused by sampler instability. If the measured value changes slowly, the median filtering method will be more effective, but if the data changes quickly, this method is not suitable.

(3) Arithmetic mean filtering algorithm

The basic principle of this algorithm is very simple, which is to take N consecutive sampling values and then perform arithmetic averaging.

The program code of the algorithm is as follows:

01 char filter()
02 {
03 int sum=0;
04 for (count=0;count<N;count++)
05 {
06 sum+=get_data();
07 delay():
08 }
09 return (char)(sum/N);
10 }
Description: The arithmetic mean filter algorithm is suitable for filtering signals with random interference. The characteristic of this signal is that it has an average value, and the signal fluctuates around a certain value. The average smoothness of the signal depends entirely on the value of N. When N is large, the smoothness is high and the sensitivity is low; when N is small, the smoothness is low, but the sensitivity is high. In order to facilitate the average value, N is generally taken as an integer power of 2 such as 4, 8, 16, 32, so that shift operations can be used instead of division in the program.

(4) Weighted average filtering algorithm

Because the "arithmetic mean filter algorithm" mentioned above has a contradiction between smoothness and sensitivity. In order to coordinate the relationship between smoothness and sensitivity, weighted average filtering can be used. Its principle is to multiply the N consecutive sampling values by different weighting coefficients and then accumulate them. The weighting coefficient is generally small at first and then large to highlight the effect of the following samplings and strengthen the system's understanding of the parameter change trend. Each weighting coefficient is a decimal less than 1 and meets the end condition that the sum is equal to 1. In this way, the cumulative sum after weighted operation is the effective sampling value. The mathematical model of weighted average digital filtering is:

Where: D is the weighted average of N sampling values; XN-i is the Ni-th sampling value; N is the number of samplings; Ci is the weighting coefficient. The weighting coefficient Ci reflects the proportion of various sampling values in the average value. Generally speaking, the later the sampling number, the greater the proportion, which can increase the proportion of new samples in the average value. The weighted average filtering method can highlight one part of the signal and resist another part of the signal to improve the sensitivity of the sampling value change.

The sample program code is as follows:

01 char code jq[N]={1,2,3,4,5,6,7,8,9,10,11,12}; //code array is the weighted coefficient table, stored in the program storage area
02 char code sum_jq=1+2+3+4+5+6+7+8+9+10+11+12;
03 char filter()
04 {
05 char count;
06 char value_buff[N];
07 int sum=0;
08 for(count=0;count<N;count++)
09 {
10 value_buff[count]=get_data();
11 delay();
12 }
13 for(count=0;count<N;count++)
14 sum+=value_buff[count]*jq[count];
15 return (char)(sum/sum_jq);
16 }
(5) Sliding average filter algorithm

The above introduction and various average filtering algorithms have one thing in common, that is, each valid sample value must be sampled several times continuously. When the sampling speed is slow, the real-time performance of the system cannot be guaranteed. The sliding average filtering algorithm introduced here only samples once, averages the sample value once and the past sample values together, and the valid sample value obtained can be put into use. If N sample values are averaged, N data temporary storage areas must be opened in the storage area. Each new data collected is stored in the temporary storage area, and the oldest data is removed at the same time. The N data saved are always the latest updated data. The use of a ring queue structure can easily implement this data storage method.

The program code is as follows:

01 char value_buff[N];
02 char i=0;
03 char filter()
04 {
05 char count;
06 int sum=0;
07 value_buff[i++]=get_data();
08 if(i==N)
09 i =0;
10 for(count=0;count<N;count++)
11 sum=value_buff[count];
12 return (char)(sum/N);
13 }
(6) Low-pass filtering

The differential equation of the ordinary hardware RC low-pass filter is expressed as a difference equation, and the software algorithm can be used to simulate the function of the hardware filter. After derivation, the low-pass filter algorithm is as follows:

Yn=a*Xn+(1-a)*Yn-1

Where Xn——this sampling value

Yn-1——The last filter output value;

, a——filter coefficient, its value is usually much smaller than 1;

Yn——The output value of this filtering.

It can be seen from the above formula that the output value of this filtering mainly depends on the output value of the last filtering (note that it is not the last sampling value, which is essentially different from the weighted average filtering). The contribution of this sampling value to the filtering output is relatively small, but it has some correction effect. This algorithm simulates the function of a low-pass filter with large inertia. The cutoff frequency of the filtering algorithm can be calculated using the following formula:

fL=a/2Pit pi is the ratio of the circumference of a circle to the circumference of a circle 3.14…

Where a——filter coefficient;

, t——sampling interval time;

For example: when t=0.5s (i.e. 2 times per second), a=1/32;

fL=(1/32)/(2*3.14*0.5)=0.01Hz

This is very effective when the target parameter is a physical quantity that changes very slowly. On the other hand, it cannot filter out dry signals that are higher than 1/2 of the sampling frequency. In this example, the sampling frequency is 2Hz, so other methods should be used to filter out dry signals above 1Hz.

The low-pass filter algorithm is similar to the weighted average filter, but there are only two weighted coefficients: a and 1-a. For the convenience of calculation, a is an integer, and 1-a is replaced by 256-a. The lowest byte of the calculation result can be discarded. Because there are only two items, a and 1-a, they are all programmed into the program in the form of immediate numbers, and no additional table is set. Although the sampling value is a unit byte (8-bit A/D). In order to ensure the accuracy of the calculation, the filter output value is represented by two bytes, one byte integer and one byte decimal. Otherwise, the output may not change because the mantissa is discarded each time.

Assume that Yn-1 is stored in 30H (integer) and 31H (decimal), and Yn is stored in 32H (integer) and 33H (decimal). The filtering procedure is as follows: Sub-Table 6.

I will stop here today, because there are many other methods for digital filtering algorithms, such as first-order lag low-pass filter (inertial filtering method), time-limited filtering, fault-tolerant redundant two-out-of-three filtering method, etc. However, due to personal ability and time constraints, I have not been able to list them one by one. In the future, I will continue to find information to improve them.

The main function of a single-chip microcomputer is to control peripheral devices and realize certain communications and data processing. However, in certain specific occasions, mathematical operations are inevitably used, although single-chip microcomputers are not good at implementing algorithms and performing complex operations. The following mainly introduces how to use single-chip microcomputers to realize digital filtering.

When the single-chip microcomputer collects data, random errors will be encountered. Random errors are caused by random interference. Their characteristics are that when measuring the same quantity under the same conditions, its size and sign will change irregularly and cannot be predicted, but the results of multiple measurements conform to statistical laws. In order to overcome the errors caused by random interference, filtering technology can be used in hardware, and software algorithms can be used to implement digital filtering in software. Filtering algorithms are often an important part of the system measurement and control algorithm, and they are very real-time.

Using digital filtering algorithms to overcome random interference errors has the following advantages:

1. Digital filtering does not require additional hardware costs, only uses one calculation process, has high reliability, and does not have impedance matching problems. In particular, digital filtering can filter very low frequency signals, which analog filters cannot do.

2. Digital filtering is implemented using software algorithms. Multiple input channels can share one filtering program, reducing system expenses.

3. As long as the filtering procedure or operation of the filter is appropriately changed, its filtering characteristics can be easily changed, which will have a greater effect on filtering out low-frequency interference and random signals.

4. The commonly used filtering algorithms in the single-chip microcomputer system include limited amplitude filtering, median filtering, arithmetic mean filtering, weighted average filtering, sliding average filtering, etc.

(1) Limiting filter algorithm

During this operation, two adjacent samples are subtracted to find their increment, and then the absolute value of the increment is compared with the maximum difference A allowed between the two samples. The size of A depends on the specific situation of the object being measured. If it is less than or equal to the maximum difference allowed, the current sampling is valid; otherwise, the last sampling value is taken as the sample of this data.

The program code of the algorithm is as follows:

01 #define A // Maximum allowed difference
02 char data; // Last data
03 char filter()
04 {
05 char datanew; // New data variable
06 datanew=get_data(); // Get new data variable
07 if( (datanew-data)>A||(data-datanew>A) )
08 return data;
09 else
10 return datanew;
11 }
Note: The limit filter method is mainly used to process data that changes slowly, such as temperature, position of an object, etc. When using it, the key is to select a suitable gate limit A. Usually this can be obtained from empirical data, and can be obtained through experiments when necessary.

(2) Median filter algorithm

The operation process is to sample a certain parameter N times continuously (N is generally an odd number), then arrange the values of the N samples from small to large, and then take the middle value as the sampling value this time. The whole process is actually a sequence sorting process.

The program code of the algorithm is as follows:

01 #define N 11 //Define the number of data obtained02
char filter()
03 {
04 char value_buff[N]; //Define an array to store data05
char count,i,j,temp;
06 for(count=0;count<N;count++) //Get data07
{
08 value_buf[count]=get_data();
09 delay(); //If the data collection is slow, then a delay or interrupt is required10
}
11
12 for(j=0;j<N-1;j++) //Sort data using the bubble method. Of course, it is best to use other sorting methods{ for(value_buff>value_buff[i+1]
13 {
14 temp=value_buff;
15 value_buff=value_buff[i+1];
16 value_buff[i+1]=temp;
17 }
18 }
19 return value_buff[(N-1)/2];
20 }
Description: Median filtering is more suitable for removing fluctuations caused by accidental factors and pulsation interference caused by sampler instability. If the measured value changes slowly, the median filtering method will be more effective, but if the data changes quickly, this method is not suitable.

(3) Arithmetic mean filtering algorithm

The basic principle of this algorithm is very simple, which is to take N consecutive sampling values and then perform arithmetic averaging.

The program code of the algorithm is as follows:

01 char filter()
02 {
03 int sum=0;
04 for (count=0;count<N;count++)
05 {
06 sum+=get_data();
07 delay():
08 }
09 return (char)(sum/N);
10 }
Description: The arithmetic mean filter algorithm is suitable for filtering signals with random interference. The characteristic of this signal is that it has an average value, and the signal fluctuates around a certain value. The average smoothness of the signal depends entirely on the value of N. When N is large, the smoothness is high and the sensitivity is low; when N is small, the smoothness is low, but the sensitivity is high. In order to facilitate the average value, N is generally taken as an integer power of 2 such as 4, 8, 16, 32, so that shift operations can be used instead of division in the program.

(4) Weighted average filtering algorithm

Because the "arithmetic mean filter algorithm" mentioned above has a contradiction between smoothness and sensitivity. In order to coordinate the relationship between smoothness and sensitivity, weighted average filtering can be used. Its principle is to multiply the N consecutive sampling values by different weighting coefficients and then accumulate them. The weighting coefficient is generally small at first and then large to highlight the effect of the following samplings and strengthen the system's understanding of the parameter change trend. Each weighting coefficient is a decimal less than 1 and meets the end condition that the sum is equal to 1. In this way, the cumulative sum after weighted operation is the effective sampling value. The mathematical model of weighted average digital filtering is:

Where: D is the weighted average of N sampling values; XN-i is the Ni-th sampling value; N is the number of samplings; Ci is the weighting coefficient. The weighting coefficient Ci reflects the proportion of various sampling values in the average value. Generally speaking, the later the sampling number, the greater the proportion, which can increase the proportion of new samples in the average value. The weighted average filtering method can highlight one part of the signal and resist another part of the signal to improve the sensitivity of the sampling value change.

The sample program code is as follows:

01 char code jq[N]={1,2,3,4,5,6,7,8,9,10,11,12}; //code array is the weighted coefficient table, stored in the program storage area
02 char code sum_jq=1+2+3+4+5+6+7+8+9+10+11+12;
03 char filter()
04 {
05 char count;
06 char value_buff[N];
07 int sum=0;
08 for(count=0;count<N;count++)
09 {
10 value_buff[count]=get_data();
11 delay();
12 }
13 for(count=0;count<N;count++)
14 sum+=value_buff[count]*jq[count];
15 return (char)(sum/sum_jq);
16 }
(5) Sliding average filter algorithm

The above introduction and various average filtering algorithms have one thing in common, that is, each valid sample value must be sampled several times continuously. When the sampling speed is slow, the real-time performance of the system cannot be guaranteed. The sliding average filtering algorithm introduced here only samples once, averages the sample value once and the past sample values together, and the valid sample value obtained can be put into use. If N sample values are averaged, N data temporary storage areas must be opened in the storage area. Each new data collected is stored in the temporary storage area, and the oldest data is removed at the same time. The N data saved are always the latest updated data. The use of a ring queue structure can easily implement this data storage method.

The program code is as follows:

01 char value_buff[N];
02 char i=0;
03 char filter()
04 {
05 char count;
06 int sum=0;
07 value_buff[i++]=get_data();
08 if(i==N)
09 i =0;
10 for(count=0;count<N;count++)
11 sum=value_buff[count];
12 return (char)(sum/N);
13 }
(6) Low-pass filtering

The differential equation of the ordinary hardware RC low-pass filter is expressed as a difference equation, and the software algorithm can be used to simulate the function of the hardware filter. After derivation, the low-pass filter algorithm is as follows:

Yn=a*Xn+(1-a)*Yn-1

Where Xn——this sampling value

Yn-1——The last filter output value;

, a——filter coefficient, its value is usually much smaller than 1;

Yn——The output value of this filtering.

It can be seen from the above formula that the output value of this filtering mainly depends on the output value of the last filtering (note that it is not the last sampling value, which is essentially different from the weighted average filtering). The contribution of this sampling value to the filtering output is relatively small, but it has some correction effect. This algorithm simulates the function of a low-pass filter with large inertia. The cutoff frequency of the filtering algorithm can be calculated using the following formula:

fL=a/2Pit pi is the ratio of the circumference of a circle to the circumference of a circle 3.14…

Where a——filter coefficient;

, t——sampling interval time;

For example: when t=0.5s (i.e. 2 times per second), a=1/32;

fL=(1/32)/(2*3.14*0.5)=0.01Hz

This is very effective when the target parameter is a physical quantity that changes very slowly. On the other hand, it cannot filter out dry signals that are higher than 1/2 of the sampling frequency. In this example, the sampling frequency is 2Hz, so other methods should be used to filter out dry signals above 1Hz.

The low-pass filter algorithm is similar to the weighted average filter, but there are only two weighted coefficients: a and 1-a. For the convenience of calculation, a is an integer, and 1-a is replaced by 256-a. The lowest byte of the calculation result can be discarded. Because there are only two items, a and 1-a, they are all programmed into the program in the form of immediate numbers, and no additional table is set. Although the sampling value is a unit byte (8-bit A/D). In order to ensure the accuracy of the calculation, the filter output value is represented by two bytes, one byte integer and one byte decimal. Otherwise, the output may not change because the mantissa is discarded each time.

Assume that Yn-1 is stored in 30H (integer) and 31H (decimal), and Yn is stored in 32H (integer) and 33H (decimal). The filtering procedure is as follows: Sub-Table 6.

I will stop here today, because there are many other methods for digital filtering algorithms, such as first-order lag low-pass filter (inertial filtering method), time-limited filtering, fault-tolerant redundant two-out-of-three filtering method, etc. However, due to personal ability and time constraints, I have not been able to list them one by one. In the future, I will continue to find information to improve them.

This post is from DSP and ARM Processors
 

Guess Your Favourite
Just looking around
Find a datasheet?

EEWorld Datasheet Technical Support

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京B2-20211791 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号
快速回复 返回顶部 Return list