How to Implement Digital Filtering Algorithms in Microcontrollers? (With Code)

How to Implement Digital Filtering Algorithms in Microcontrollers? (With Code)ID: Technology Makes Dreams GreaterCompiled by: Li Xiaoyao

The main function of a microcontroller is to control peripheral devices and achieve certain communication and data processing.However, in certain specific situations, mathematical operations are inevitably required, even though microcontrollers are not adept at implementing algorithms and performing complex calculations.This article mainly introduces how to implement digital filtering using microcontrollers.When collecting data with a microcontroller, random errors in the data may occur. Random errors are caused by random interference, characterized by unpredictable changes in magnitude and sign when measuring the same quantity under the same conditions, but the results of multiple measurements conform to statistical laws.To overcome errors caused by random interference, filtering techniques can be employed in hardware, while software algorithms can be used to implement digital filtering. Filtering algorithms are often an important component of system measurement and control algorithms, requiring real-time performance.How to Implement Digital Filtering Algorithms in Microcontrollers? (With Code)Using digital filtering algorithms to overcome errors from random interference has the following advantages:

  1. Digital filtering does not require additional hardware costs; it only involves a computational process, ensuring high reliability without impedance matching issues. In particular, digital filtering can filter very low-frequency signals, which is not possible with analog filters.

  2. Digital filtering is implemented using software algorithms, allowing multiple input channels to share a single filtering program, reducing system costs.

  3. By appropriately modifying the filtering program or calculations, the filtering characteristics can be easily changed, which is effective for eliminating low-frequency interference and random signals.

  4. Common filtering algorithms used in microcontroller systems include limit filtering, median filtering, arithmetic mean filtering, weighted average filtering, and moving average filtering.

How to Implement Digital Filtering Algorithms in Microcontrollers? (With Code)Limit Filtering Algorithm

In this operation, the difference between two adjacent samples is calculated to find the increment, which is then compared to the maximum allowable difference A between the two samples.The value of A depends on the specific situation of the measured object; if it is less than or equal to the maximum allowable difference, the current sample is valid; otherwise, the previous sample value is taken as the current data sample.The algorithm’s code is as follows:

 1#define A // Maximum allowable difference
 2
 3char data; // Previous data
 4
 5char filter()
 6
 7{
 8
 9    char datanew; // New data variable
10
11    datanew=get_data(); // Get new data variable
12
13    if((datanew-data)>A||(data-datanew>A))
14
15        return data;
16
17    else
18
19        return datanew;
20
21}

Note:The limit filtering method is mainly used for processing data that changes slowly, such as temperature or the position of an object. When using it, it is crucial to select an appropriate limit A. This can usually be obtained from empirical data and, if necessary, through experimentation.

How to Implement Digital Filtering Algorithms in Microcontrollers? (With Code)Median Filtering Algorithm

The process of this operation involves continuously sampling a parameter N times (N is generally an odd number), sorting the N sampled values in ascending order, and taking the middle value as the current sample value. The entire process is essentially a sequence sorting process.The algorithm’s code is as follows:

 1#define N 11 // Define the number of data samples
 2 3char filter()
 4
 5{
 6 7    char value_buff[N]; // Define an array to store data
 8 9    char count,i,j,temp;
1011    for(count=0;count<N;count++)
1213    {
1415        value_buf[count]=get_data();
1617        delay(); // If data collection is slow, a delay or interrupt is needed
1819    }
2021    for(j=0;j<N;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    }
3839return value_buff[(N-1)/2];
4041}

Note:Median filtering is particularly suitable for removing fluctuations caused by random factors and pulsations due to unstable samplers. If the measured value changes slowly, the median filtering method will be more effective; however, if the data changes rapidly, this method is not advisable.

How to Implement Digital Filtering Algorithms in Microcontrollers? (With Code)Arithmetic Mean Filtering Algorithm

The basic principle of this algorithm is straightforward: it continuously takes N sample values and computes their arithmetic mean.The algorithm’s code is as follows:

 1char filter()
 2
 3{
 4
 5    int sum=0;
 6
 7    for(count=0;count<N;count++)
 8
 9    {
10
11        sum+=get_data();
12
13        delay();
14
15    }
16
17    return (char)(sum/N);
18
19}

Note:The arithmetic mean filtering algorithm is suitable for filtering signals with random interference. Such signals are characterized by having an average value, with the signal fluctuating around a certain value.The degree of smoothing of the signal is entirely dependent on the value of N. When N is large, the smoothing is high, but sensitivity is low; when N is small, the smoothing is low, but sensitivity is high. To facilitate averaging, N is generally taken as powers of 2, such as 4, 8, 16, 32, to allow for bit-shifting operations in the program instead of division.

How to Implement Digital Filtering Algorithms in Microcontrollers? (With Code)Weighted Average Filtering Algorithm

Due to the aforementioned contradictions between smoothing and sensitivity in the “arithmetic mean filtering algorithm,” weighted average filtering can be used to reconcile the relationship between smoothing and sensitivity.The principle is to multiply each of the continuous N sample values by different weighting coefficients before summing them up. The weighting coefficients are generally arranged from small to large to emphasize the effect of the later samples, enhancing the system’s recognition of the trend of parameter changes.Each weighting coefficient is a decimal less than 1, and they must satisfy the condition that their sum equals 1. Thus, the accumulated sum after the weighted operation is the effective sample value. The mathematical model for weighted average digital filtering is:In the formula: D is the weighted average of N sample values; XN-i is the N-i-th sample value; N is the number of samples; Ci is the weighting coefficient. The weighting coefficient Ci reflects the proportion of each sample value in the average.Generally, the later the sampling, the larger the proportion taken, which increases the weight of the new sample in the average.The weighted average filtering method can emphasize one part of the signal while suppressing another part, thereby improving the sensitivity of changes in sample values.Sample program code is as follows:

 1char codejq[N]={1,2,3,4,5,6,7,8,9,10,11,12}; // Code array for weighting coefficients, stored in program memory
 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<N;count++)
16
17    {
18
19        value_buff[count]=get_data();
20
21        delay();
22
23    }
24
25    for(count=0;count<N;count++)
26
27        sum+=value_buff[count]*jq[count];
28
29    return (char)(sum/sum_jq);
30
31}

How to Implement Digital Filtering Algorithms in Microcontrollers? (With Code)Moving Average Filtering Algorithm

The various average filtering algorithms introduced above share a common point: each time an effective sample value is obtained, several samples must be taken continuously. When the sampling speed is slow, the system’s real-time performance cannot be guaranteed.The moving average filtering algorithm introduced here samples only once, averaging the current sample value with several previous sample values to obtain an effective sample value that can be used immediately.If N sample values are taken for averaging, a temporary storage area for N data must be allocated in memory.Each time a new data point is collected, it is stored in the temporary area, while the oldest data point is discarded, ensuring that these N data points are always the most recently updated data. A circular queue structure can conveniently implement this data storage method.The program code is as follows:

 1char value_buff[N];
 2
 3char i=0;
 4
 5char 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<N;count++)
20
21        sum=value_buff[count];
22
23    return (char)(sum/N);
24
25}

How to Implement Digital Filtering Algorithms in Microcontrollers? (With Code)Low-Pass Filtering

The differential equation of a standard hardware RC low-pass filter can be expressed using a difference equation, allowing software algorithms to simulate the functionality of hardware filtering. After derivation, the low-pass filtering algorithm is as follows:

1Yn=a* Xn+(1-a) *Yn-1
2
3Where Xn——Current sample value
4
5Yn-1——Previous filtering output value;
6
7a——Filtering coefficient, typically much less than 1;
8
9Yn——Current filtering output value.

From the above formula, it can be seen that the current filtering output value mainly depends on the previous filtering output value (note that it is not the previous sample value, which is fundamentally different from weighted average filtering). The contribution of the current sample value to the filtering output is relatively small, but it does have some corrective effect. This algorithm simulates the functionality of a low-pass filter with significant inertia. The cutoff frequency of the filtering algorithm can be calculated using the following formula:

1fL=a/2Pit // where pi is approximately 3.14...
2
3Where a——Filtering coefficient;
4
5t——Sampling interval time;
6
7For example: when t=0.5s (i.e., 2 samples per second), a=1/32;
8
9fL=(1/32)/(2*3.14*0.5)=0.01Hz

When the target parameter is a slowly changing physical quantity, this is very effective. On the other hand, it cannot filter out noise signals above 1/2 the sampling frequency; in this example, the sampling frequency is 2Hz, so noise signals above 1Hz should be filtered out using other methods.The low-pass filtering algorithm is similar to the weighted average filtering, but the weighting coefficients only have two values: a and 1-a. For computational convenience, a is taken as an integer, and 1-a is replaced with 256-a, allowing the calculation result to discard the least significant byte. Since there are only two terms, a and 1-a, they can be directly embedded in the program as immediate values without needing a separate table.Although the sample value is a single byte (8-bit A/D), to ensure computational accuracy, the filtering output value is represented using two bytes, one byte for the integer part and one byte for the fractional part; otherwise, the output may not change due to discarding the fractional part each time.Assuming Yn-1 is stored in memory locations 30H (integer) and 31H (fraction), and Yn is stored in 32H (integer) and 33H (fraction).How to Implement Digital Filtering Algorithms in Microcontrollers? (With Code)Click to view previous content(Follow Chip Home)

Previous Excellent Articles

Chip Home Selected Article Collection (1): Save it for later

Chip Home Selected Article Collection (2): Save it for later

Click to read👆

How to Implement Digital Filtering Algorithms in Microcontrollers? (With Code)

How to Implement Digital Filtering Algorithms in Microcontrollers? (With Code)

Leave a Comment