Hardware filter design and software filter design in embedded development

What types of filtering are there?

Answer: The analog input signals of microcomputer control systems generally contain various noises and interferences, which come from the measured signal source itself, sensors, external interference, etc. For accurate measurement and control, noise and interference must be eliminated from the signal being measured:

Filtering is divided into hardware filtering and software filtering:

l Hardware filtering: Use analog filters such as RC filters composed of resistors and capacitors of certain specifications or LC filters composed of inductors and capacitors for filtering;

l Software filtering: also known as digital filtering, which reduces or weakens the impact of noise through certain calculation or judgment procedures. 1. What types of filtering are there?

Answer: The analog input signals of microcomputer control systems generally contain various noises and interferences, which come from the measured signal source itself, sensors, external interference, etc. For accurate measurement and control, noise and interference must be eliminated from the signal being measured:

Filtering is divided into hardware filtering and software filtering:

l Hardware filtering: Use analog filters such as RC filters composed of resistors and capacitors of certain specifications or LC filters composed of inductors and capacitors for filtering;

l Software filtering: also known as digital filtering, which reduces or weakens the impact of noise through certain calculation or judgment procedures.

Hardware filtering

What is a filter?

Various sensor signals will carry some noise signals to some extent, so the filter can better reduce and remove the noise and restore the true and useful signals.

A filter is a circuit that removes or "filters out" a specific range of frequency components. In other words, it separates the frequency spectrum of the signal into frequency components that will be passed and frequency components that will be blocked.

If you don't have much experience with frequency domain analysis, you may still be unsure of what these frequency components are and how they coexist in a signal that cannot have multiple voltage values ​​at the same time. Let's look at a short example that will help clarify this concept.

Suppose we have an audio signal consisting of a perfect 5kHz sine wave. We know what a sine wave looks like in the time domain, in the frequency domain we only see a frequency "spike" at 5kHz. Now let's assume we activate a 500kHz oscillator to introduce high frequency noise into the audio signal.

The signal seen on the oscilloscope is still just a sequence of voltages, with one value at each moment, but the signal will look different because its time domain changes must now reflect the 5kHz sine wave and the high frequency noise fluctuations.

However, in the frequency domain, sine waves and noise are separate frequency components that exist simultaneously in a signal. Sine waves and noise occupy different parts of the frequency domain representation of the signal, which means we can filter out the noise through circuits that direct the signal through low frequencies and block high frequencies. The schematic diagram of the distribution of different parts of the frequency domain of the sine wave and noise signals is as follows.

picture

Filter type

Filters can be placed into broad categories that correspond to general characteristics of the filter's frequency response. If the filter passes low frequencies and blocks high frequencies, it is called a low-pass filter; if it blocks low frequencies and passes high frequencies, it is a high-pass filter. There are also bandpass filters, which only pass a relatively narrow range of frequencies, and bandstop filters, which only block a relatively narrow range of frequencies. The frequency domain representation of each filter is shown in the figure below.

picture

Filters can also be classified based on the type of components used to implement the circuit. Passive filters use resistors, capacitors and inductors, these components are not equipped to provide amplification, so passive filters can only maintain or reduce the amplitude of the input signal. On the other hand, an active filter can both filter a signal and apply gain as it includes active components such as transistors or operational amplifiers as shown in the figure below.

picture

This active low-pass filter is based on the popular Sallen-Key topology. Related articles go here: Sallen-Key Active Filters .

RC low pass filter

To create a passive low-pass filter, we need to combine resistive elements with reactive elements. In other words, we need a circuit made up of resistors and capacitors or inductors. In theory, a resistor-inductor (RL) low-pass topology is comparable to a resistor-capacitor (RC) low-pass topology in terms of filtering capabilities. But in practice, the resistor-capacitor scheme is more common, so the remainder of this article will focus on RC low-pass filters. The schematic diagram of the RC low-pass filter is as follows.

picture

As shown in the figure, an RC low-pass response can be produced by placing a resistor in series with the signal path and a capacitor in parallel with the load. In the diagram, the load is a single component, but in a real circuit it may be more complex, such as an analog-to-digital converter, an amplifier, or the input stage of an oscilloscope used to measure the response of a filter.

If we realize that the resistor and capacitor form a frequency-dependent voltage divider, we can intuitively analyze the filtering action of the RC low-pass topology. Redraw the RC low-pass filter so that it looks like a voltage divider, as shown below.

picture

When the frequency of the input signal is low, the impedance of the capacitor is high relative to the impedance of the resistor; therefore, most of the input voltage drops across the capacitor (and across the load, in parallel with the capacitor). When the input frequency is high, the impedance of the capacitor is lower relative to the impedance of the resistor, which means that the voltage across the resistor is reduced and less voltage is transferred to the load. Therefore, low frequencies pass and high frequencies are blocked.

This qualitative explanation of the low-pass function of an RC is an important first step, but it's not very useful when we need to actually design circuits because the terms "high frequency" and "low frequency" are very vague. Engineers need to create circuits that pass and block specific frequencies. For example, in the above audio system we want to preserve the 5kHz signal and reject the 500kHz signal. This means we need a filter that transitions from pass to block between 5kHz and 500kHz.

RC filter cutoff frequency

The frequency range in which the filter does not cause significant attenuation is called the passband, and the frequency range in which the filter does cause significant attenuation is called the stopband. Analog filters, such as RC low-pass filters, always transition gradually from the passband to the stopband. This means there is no way to identify a frequency at which the filter stops passing the signal and starts blocking it. However, engineers need a convenient and concise way to summarize the frequency response of a filter, and this is where the concept of cutoff frequency comes into play.

When you look at the frequency response plot of an RC filter, you'll notice that the term "cutoff frequency" is not very accurate. An image in which the signal spectrum is "cut" into two halves, one of which is retained and one of which is discarded, is not applicable because the attenuation gradually increases as the frequency moves from below to above the cutoff.

The cutoff frequency of an RC low-pass filter is actually the frequency at which the input signal amplitude is reduced by 3dB (this value was chosen because a 3dB reduction in amplitude corresponds to a 50% reduction in power). Therefore, the cutoff frequency is also called the -3dB frequency, which is actually a more accurate and informative name. The term bandwidth refers to the width of the filter passband, which in the case of a low-pass filter is equal to the -3dB frequency as shown in the figure below.

picture

The above figure shows the general characteristics of the frequency response of an RC low-pass filter with a bandwidth equal to -3dB frequency.

As mentioned above, the low-pass behavior of an RC filter is caused by the interaction between the frequency-independent impedance of the resistor and the frequency-dependent impedance of the capacitor. To determine the details of a filter's frequency response, we need to mathematically analyze the relationship between resistance (R) and capacitance (C). We can also manipulate these values ​​to design a filter that meets precise specifications. The cutoff frequency (fC) of the RC low-pass filter is calculated as follows:

picture

Let’s look at a simple design example. Capacitor values ​​are more restrictive than resistor values, so we'll start with a common cap value such as 10nF, and then we'll use that formula to determine the required resistor value. The goal is to design a filter that will preserve the 5kHz audio waveform and suppress the 500kHz noise waveform. We will experiment with a cutoff frequency of 100kHz, later in the article we will analyze more closely the effect of this filter on the two frequency components, the formula is as follows.

picture

Therefore, the 160Ω resistor combined with the 10nF capacitor will give us a filter that is very close to the desired frequency response.

Filter response visualization

The most convenient way to evaluate the effect of a filter on a signal is to examine a plot of the filter's frequency response. These graphs are often called Bode plots and have magnitude (in decibels) on the vertical axis and frequency on the horizontal axis; the horizontal axis usually has a logarithmic scale such that the physical distance between 1Hz and 10Hz is the same as that between 10Hz and Same physical distance between 100Hz, 100Hz and 1kHz etc. This configuration allows us to quickly and accurately evaluate the filter's behavior over a wide frequency range. The figure below is an example of a frequency response diagram.

picture

Each point on the curve represents the amplitude the output signal would have if the amplitude of the input signal was 1V and the frequency was equal to the corresponding value on the horizontal axis. For example, when the input frequency is 1MHz, the output amplitude (assuming an input amplitude of 1V) will be 0.1V (since -20dB corresponds to a tenfold reduction factor).

The general shape of this frequency response curve will become very familiar as you spend more time with filter circuits. The curve in the passband is almost perfectly flat, then it starts to fall off faster as the input frequency approaches the cutoff frequency. Eventually, the rate of change of attenuation (called roll-off) stabilizes at 20dB/decade—that is, for every tenfold increase in input frequency, the amplitude of the output signal decreases by 20dB.

Evaluate low-pass filter performance

If we carefully plot the frequency response of the filter we designed earlier in this article, we will see that the magnitude response at 5kHz is essentially 0dB (i.e. almost zero attenuation), and at 500kHz is about -14dB (corresponding to 0.2 gain). These values ​​are consistent with the calculations we performed in the previous section.

Since RC filters always have a gradual transition from passband to stopband, and because the attenuation never reaches infinity, we cannot design a "perfect" filter—that is, one that has no effect on the sine wave and completely eliminates noise. Instead, we always need to make trade-offs. If we move the cutoff frequency closer to 5kHz we will have more noise attenuation, but also more attenuation of the sine wave we want to send to the speaker. If we move the cutoff frequency closer to 500kHz, we have less attenuation at sine wave frequencies, but also less attenuation at noise frequencies.

Previously we have discussed the ways in which filters modify the amplitude of various frequency components in a signal. However, in addition to amplitude effects, reactive circuit elements always introduce phase shifts.

low pass filter phase shift

The concept of phase refers to the value of a periodic signal at a specific moment in a cycle. So when we say that a circuit causes a phase shift, we mean that it creates a deviation between the input signal and the output signal: the input and output signals no longer start and end their periods at the same moment. A phase shift value (such as 45° or 90°) indicates the amount of offset produced.

Each reactive element in the circuit introduces a 90° phase shift, but this phase shift does not occur simultaneously. The phase of the output signal, like the amplitude of the output signal, gradually changes as the input frequency increases. There is a reactive element (capacitor) in the RC low pass filter, so the circuit also ends up introducing a 90° phase shift.

As with the amplitude response, the phase response is most easily evaluated by examining a plot with the horizontal axis representing logarithmic frequency. The following description represents the general pattern, see the image below for further details.

  • The phase shift is initially 0°
  • The phase shift gradually increases until it reaches 45° at the cutoff frequency, and during this part of the response the rate of change gradually increases
  • After the cutoff frequency, the phase shift continues to increase, but the rate of change gradually decreases
  • As the phase shift gradually approaches 90°, the rate of change becomes very small

picture

The solid line is the amplitude response and the dashed line is the phase response. The cutoff frequency is 100kHz. Note that the phase shift at the cutoff frequency is 45°.

Second order low pass filter

So far, we have assumed that the RC low pass filter consists of a resistor and a capacitor. This configuration is a first-order filter. related suggestion:

The "order" of a passive filter is determined by the number of reactive components (i.e. capacitors or inductors) in the circuit. Higher-order filters have more reactive components, resulting in more phase shifts and steeper roll-offs, the latter being the main motivation for increasing filter order.

Adding a reactive element to the filter, for example, from first order to second order or second order to third order, increases the maximum roll-off by 20dB/decade.

Second-order filters are usually built around a resonant circuit consisting of an inductor and a capacitor, a topology called RLC (Resistor-Inductor-Capacitor). However, it is also possible to create second-order RC filters. As shown in the figure below, all we need to do is cascade two first-order RC filters.

picture

While this topology certainly produces a second-order response, it is not widely used and its frequency response is generally not as good as a second-order active filter or a second-order RLC filter.

Frequency Response of Second Order RC Filter

We can try to design a first-order filter according to the required cutoff frequency, and then select two of them to connect in series to form a second-order RC low-pass filter. This does allow the filter to exhibit a similar overall frequency response, with a maximum rolloff of 40dB/decade instead of 20dB/decade.

However, if we look more closely at the response, we see a reduction in the -3dB frequency. The second-order RC filter does not behave as expected because the two filtering stages are not independent, so one cannot simply connect the two filters together and analyze the circuit as a first-order low-pass filter superimposed with an identical Low-pass filtering.

Furthermore, even if we insert a buffer between the two stages so that the first-order RC and the second-order RC can be used as independent filters, the attenuation at the original cutoff frequency will be 6dB instead of 3dB. This is precisely because the two stages work independently. The first filter has 3dB of attenuation at the cutoff frequency, while the second filter adds another 3dB of attenuation, as shown below.

picture

A fundamental limitation of second-order RC lowpass filters is that the designer cannot fine-tune the transition from the passband to the stopband by adjusting the filter's Q-factor; this parameter indicates how damped the frequency response is. If two identical RC low-pass filters are cascaded, the overall transfer function corresponds to a second-order response, but the Q-factor is always 0.5. With Q=0.5, the filter is on the borderline of being overdamped, which causes the frequency response to "droop" in the transition region. Second-order active filters and second-order resonant filters do not have this limitation; designers can control the Q factor to fine-tune the frequency response in the transition region.

Summarize

All electrical signals contain a mixture of desired frequency components and unwanted frequency components. Unwanted frequency components are often caused by noise and interference, and in some cases can negatively impact the performance of the system.

Filters are circuits that react in different ways to different parts of a signal's spectrum. A low-pass filter is designed to pass low-frequency components while blocking high-frequency components.

The cutoff frequency of a low-pass filter indicates the frequency region where the filter changes from low attenuation to significant attenuation.

The output voltage of an RC low-pass filter can be calculated by considering the circuit as a voltage divider consisting of a (frequency-independent) resistor and a (frequency-dependent) reactance.

A plot of amplitude (in dB, on the vertical axis) versus logarithmic frequency (in Hz, on the horizontal axis) is a convenient and efficient way to check the theoretical behavior of a filter. Phase versus logarithmic frequency can also be used. diagram to determine the amount of phase shift that will be applied to the input signal.

Second-order filters have a steeper roll-off; this second-order response is useful when the signal does not provide broadband separation between desired and undesired frequency components.

It is possible to create a second order RC low pass filter by building two identical first order RC low pass filters and then connecting the output of one to the input of the other, but you will end up with a lower overall -3dB frequency than expected.

Software filtering

Filtering method method advantage shortcoming the complexity
clipping filter Based on empirical judgment, determine the maximum allowable deviation value for two samplings to be A, and judge each time a new value is detected; if the difference between this value and the last value is <= A, it is valid; if the difference between this value and the last value is If the difference in values ​​is >A, then this value is invalid, discard this value, and replace this value with the last value. Can effectively overcome pulse interference caused by accidental factors Unable to suppress periodic interference, poor smoothness Not calculated yet
median filter method Continuously sample N times (N is an odd number), arrange the N sample values ​​according to size, and take the middle value as the effective value this time. It can effectively overcome fluctuation interference caused by accidental factors, and has a good filtering effect on measured parameters that change slowly in temperature and liquid level. Not suitable for rapidly changing parameters such as flow rate and speed
Arithmetic mean filtering method Continuously sample N values ​​for arithmetic average calculation; when the N value is large: the signal smoothness is high, but the sensitivity is low; when the N value is small: the signal smoothness is low, but the sensitivity is high; N value selection: general flow, N = 12; Pressure: N = 4 It is suitable for filtering signals that generally have random interference, such that the signal is characterized by an average value, and the signal fluctuates around a certain value range It is not suitable for trial control with slow measurement speed or fast data calculation speed, which is a waste of RAM
recursive average filtering method Treat N consecutive sampling values ​​as a queue; the length of the queue is fixed at N; each time a new data is sampled, it is put into the end of the queue, and the original data at the head of the queue is discarded (first in, first out); the data in the queue is Calculate the arithmetic average of N data to get a new filtering result; N is worth selecting: flow: N = 12; pressure: N = 4; liquid level: N = 4-12; temperature: N = 1-4 It has good suppression effect on periodic interference, high smoothness, and is suitable for systems with high-frequency oscillations. Low sensitivity, poor suppression of occasional pulse interference, difficult to eliminate sampling value deviation caused by pulse interference, not suitable for occasions with serious pulse interference, waste of RAM
Median average filtering method Equivalent to "median filtering method + arithmetic mean filtering method", continuously sample N data, remove a maximum value and a minimum value and then calculate the arithmetic mean of N-2 data, N = 3-14 It combines the advantages of two types of filtering to eliminate sampling value deviations caused by occasional impulsive filtering interference. The measurement speed is slow, just like the arithmetic mean filter, it is a waste of RAM
clipped average filtering method It is equivalent to "limiting two parts + recursive average filtering method". Each time the new data is sampled, it is first subjected to clipping processing, and then sent to the queue for recursive average filtering processing. It combines the advantages of two types of filtering to eliminate sampling value deviations caused by occasional impulsive filtering interference. A waste of RAM
First-order lag filtering method Take a = 0-1, (1-a) this sampling value + a last filtering result It has good suppression effect on periodic interference and is suitable for occasions with high fluctuation frequency. Phase lag, low sensitivity, the degree of lag depends on the size of a, and it cannot eliminate interference signals with a filtering frequency higher than 1/2 of the sampling frequency
weighted recursive average filtering method It is an improvement on the recursive average filtering method, that is, different weights are given to data at different times. Usually, the closer to the data at the current time, the greater the weight. The greater the weight coefficient given to the new sample value, the higher the sensitivity, but the lower the smoothness of the signal. Suitable for systems with large pure lag time constants For signals with small pure delay time constants, long sampling periods, and slowly changing signals, the severity of the current interference to the system cannot be quickly reflected, and the filtering effect is poor.
Anti-bounce filtering method Set a filter counter to compare each sampling value with the current effective value: if the sampling value = the current effective value, the counter is cleared; if the sampling value </> is the current effective value, the counter is +1, and it is judged whether the counter is >= Upper limit N (overflow); if the counter overflows, replace the current valid value with this value and clear the counter For slowly changing measured parameters, the better filtering effect can avoid repeated on/off jumps of the controller near the critical value or numerical jitter on the display. It is not suitable for fast-changing parameters. If the sampling value happens to be a disturbance value when the counter overflows, the disturbance value will be imported into the system as an effective value.
Limiting debounce filtering method Equivalent to "limiting filter method + debounce filter method", first limit, then debounce Inheriting the advantages of limiting and debounce, it improves the defects in the debounce filtering method and avoids introducing interference values ​​into the system. Not suitable for rapidly changing parameters
Butterworth filter Suitable for AD sampling, periodic pulse fluctuations will occur Occupies too much RAM, takes a long time to calculate, and is not suitable for rapidly changing parameters.

Edited from: https://www.jianshu.com/p/38ed6ff1b8c0

Name: Wang Keyi

Student ID: 20021110373T

Reprinted from: http://www.wtoutiao.com/p/1fe9dPI.html

[Introduction to Embedded Niu] Summarizes the characteristics and scope of application of some commonly used digital filtering algorithms.

[Embedded Bull’s Nose] 1. Digital filtering method to overcome large pulse interference; 2. Average filtering method to suppress small-amplitude high-frequency noise; 3. Composite filtering method

[embedded cow text]

Digital filtering: Use digital equipment to process signals through certain algorithms to filter out signals in a certain frequency band and obtain new signals. This process is called digital filtering.

Digital filters can be divided into two parts: classic filters and modern filters. The classical filter assumes that the useful components and the desired filtered components in the input signal x(n) are located in different frequency bands. Therefore, we can filter the noise through a linear system. If the spectrum of the noise and the signal overlap each other, Then the classical filter cannot meet the filtering requirements. There are usually high pass filters, low pass filters, band pass filters, and band stop filters. Modern filters estimate useful signals and noise signals from noisy signals. This method treats both the signal and the noise themselves as random signals, uses their statistical characteristics, such as autocorrelation function, cross-correlation function, autopower spectrum, cross-power spectrum, etc., to guide the signal estimation algorithm, and then uses digital equipment to implement it. At present, there are mainly digital filters such as Wiener filter, Kalman filter, and adaptive filter.

The following introduces 8 commonly used filtering methods:

(1) Digital filtering method to overcome large pulse interference:

Overcoming the sharp pulse interference caused by sudden disturbances caused by accidental factors in the external environment of the instrument or bit errors caused by internal instability of the instrument is the first step in instrument data processing. Usually a simple nonlinear filtering method is used.

1. Limiting filtering method (also known as program judgment filtering method) limiting filtering is to judge the change amplitude of the measured signal through a program, thereby eliminating the sharp pulse interference in the slowly changing signal.

A. Method: Based on empirical judgment, determine the maximum deviation value allowed for two samplings (set to A). Judge each time a new value is detected: If the difference between this value and the previous value is A, then this value is invalid and given up. This value, replace this value with the last value

B. Advantages: It can effectively overcome pulse interference caused by accidental factors. Disadvantages: Unable to suppress periodic interference and poor smoothness.

C. Scope of application: measured values ​​that change slowly

2. Median filtering method

The median filter is a typical nonlinear filter. It has a simple operation and can well protect the detailed information of the signal while filtering out impulse noise.

A. Method: Continuously sample N times (N is an odd number), arrange the N sampled values ​​according to size (bubble method is often used), and take the middle value as the effective value this time.

B. Advantages: It can effectively overcome fluctuation (pulse) interference caused by accidental factors. Disadvantages: Not suitable for rapidly changing parameters such as flow rate and speed.

C. Scope of application: It has good filtering effect on measured parameters that change slowly in temperature and liquid level.

(2) Average filtering method to suppress small-amplitude high-frequency noise

Small-amplitude high-frequency electronic noise: electronic device thermal noise, A/D quantization noise, etc. Linear filters with low-pass characteristics are usually used: arithmetic average filtering method, weighted average filtering method, sliding weighted average filtering method, first-order lag filtering method, etc.

3. Arithmetic average filtering method The arithmetic average filtering method is to add N consecutive sampling values, and then take the arithmetic average as the filtered value of this measurement.

A. Method: Continuously take N sample values ​​and perform arithmetic average calculation. When the N value is larger: the signal smoothness is higher, but the sensitivity is lower. When the N value is smaller: the signal smoothness is lower, but the sensitivity is higher. Selection of the N value: General flow rate, N=12; pressure: N=4

B. Advantages: It is very effective in filtering out random interference signals mixed in the measured signal. The characteristic of the measured signal is that it has an average value, and the signal fluctuates up and down around a certain value range. Disadvantages: It is not easy to eliminate errors caused by pulse interference. For real-time systems that have slow sampling speeds or require high data update rates, the arithmetic mean filtering method cannot be used. A waste of RAM

4. Recursive average filtering method (also known as moving average filtering method)

For real-time systems that have slow sampling speeds or require high data update rates, the arithmetic mean filtering method cannot be used. The moving average filter method treats N measurement data as a queue. The length of the queue is fixed at N. Every time a new sampling is performed, the measurement result is placed at the end of the queue and the data at the head of the original queue is removed, so that it is always in the queue. There are N "latest" data.

A. Method: Treat N consecutive sampling values ​​as a queue. The length of the queue is fixed at N. Each time a new data is sampled, it is put into the end of the queue, and the original data at the head of the queue is thrown away. (First in, first out principle ) Perform an arithmetic average operation on the N data in the queue to obtain a new filtering result. Selection of N values: flow rate, N=12; pressure: N=4; liquid level, N=4 12; temperature, N= 1 4

B. Advantages: It has a good suppression effect on periodic interference, high smoothness and is suitable for high-frequency oscillation systems. Disadvantages: low sensitivity, poor suppression of occasional pulse interference, difficult to eliminate sampling value deviation caused by pulse interference, not suitable for occasions with serious pulse interference, waste of RAM

5. Weighted recursive average filtering method

A. Method: It is an improvement on the recursive average filtering method, that is, different weights are assigned to data at different times. Usually, the closer to the data at the current time, the greater the weight. The greater the weight coefficient given to the new sample value, the higher the sensitivity, but the smoothness of the signal is low.

B. Advantages: It is suitable for objects with large pure delay time constants and systems with short sampling periods. Disadvantages: For the pure lag time constant is small, the sampling period is long, the slow-changing signal cannot quickly reflect the severity of the current interference of the system, and the filtering effect is poor

6. First-order lag filtering method The first-order low-pass digital filter uses software to implement hardware RC filtering to suppress interference signals. In analog input channels, first-order lag RC analog filters are commonly used to suppress interference.

When using this method to achieve low-frequency interference, the first problem encountered is that the filter is required to have a large time constant (time constant = RC) and a high-precision RC network. The larger the time constant, the larger the RC value required, and the leakage current will inevitably increase, thus reducing the accuracy of the RC network. The digital filtering method with first-order lag can well overcome the shortcomings of this analog filter. This method is more suitable when the filter constant requirements are large.

A. Method: a=Tf/(Tf+T)Tf is the filtering time constant. T is the sampling period. This filtering result = (1-a) this sampling value + a last filtering result.

B. Advantages: It has good suppression effect on periodic interference and is suitable for occasions with high fluctuation frequency. Disadvantages: Phase lag, low sensitivity. The degree of lag depends on the value of a. Interfering signals with a filtering frequency higher than 1/2 of the sampling frequency cannot be eliminated.

(3) Composite filtering method

In practical applications, sometimes it is necessary to eliminate large-scale pulse interference and achieve data smoothing. Therefore, two or more methods introduced previously are often used in combination to form composite filtering. De-extreme average filtering algorithm: First use the median filter algorithm to filter out the impulsive interference in the sampled values, and then average the remaining sampled values. Continuously sample N times, eliminate the maximum and minimum values, and then find the average of the remaining N-2 samples. Obviously, this method can suppress random interference and filter out obvious pulse interference.

7. Median average filtering method (also known as anti-pulse interference average filtering method)

The median average filter method is equivalent to the "median value filter method" + "arithmetic average filter method".

A. Method: Continuously sample N data, remove a maximum value and a minimum value, and then calculate the arithmetic mean of N-2 data. Selection of N value: 3~14

B. Advantages: It combines the advantages of two filtering methods. This method can not only suppress random interference, but also filter out obvious pulse interference. Disadvantages: The measurement speed is slow, and like the arithmetic mean filtering method, it wastes RAM.

8. Limiting average filtering method

In situations where pulse interference is severe, if the general average method is used, the interference will be averaged into the result. Limiting average filtering method is equivalent to "limiting filtering method" + "recursive average filtering method"

A. Method: Each new sampled data is first subjected to limiting processing, and then sent to the queue for recursive average filtering processing.

B. Advantages: It combines the advantages of the two filtering methods. For the occasional pulse interference, the sampling value deviation caused by the pulse interference can be eliminated. Disadvantages: a waste of RAM

C. Scope of application: The slowly changing signal has been edited from: https://www.jianshu.com/p/38ed6ff1b8c0

Name: Wang Keyi

Student ID: 20021110373T

Reprinted from: http://www.wtoutiao.com/p/1fe9dPI.html

[Introduction to Embedded Niu] Summarizes the characteristics and scope of application of some commonly used digital filtering algorithms.

[Embedded Bull’s Nose] 1. Digital filtering method to overcome large pulse interference; 2. Average filtering method to suppress small-amplitude high-frequency noise; 3. Composite filtering method

[embedded cow text]

Digital filtering: Use digital equipment to process signals through certain algorithms to filter out signals in a certain frequency band and obtain new signals. This process is called digital filtering.

Digital filters can be divided into two parts: classic filters and modern filters. The classical filter assumes that the useful components and the desired filtered components in the input signal x(n) are located in different frequency bands. Therefore, we can filter the noise through a linear system. If the spectrum of the noise and the signal overlap each other, Then the classical filter cannot meet the filtering requirements. There are usually high pass filters, low pass filters, band pass filters, and band stop filters. Modern filters estimate useful signals and noise signals from noisy signals. This method treats both the signal and the noise themselves as random signals, uses their statistical characteristics, such as autocorrelation function, cross-correlation function, autopower spectrum, cross-power spectrum, etc., to guide the signal estimation algorithm, and then uses digital equipment to implement it. At present, there are mainly digital filters such as Wiener filter, Kalman filter, and adaptive filter.

The following introduces 8 commonly used filtering methods:

(1) Digital filtering method to overcome large pulse interference:

Overcoming the sharp pulse interference caused by sudden disturbances caused by accidental factors in the external environment of the instrument or bit errors caused by internal instability of the instrument is the first step in instrument data processing. Usually a simple nonlinear filtering method is used.

1. Limiting filtering method (also known as program judgment filtering method) limiting filtering is to judge the change amplitude of the measured signal through a program, thereby eliminating the sharp pulse interference in the slowly changing signal.

A. Method: Based on empirical judgment, determine the maximum deviation value allowed for two samplings (set to A). Judge each time a new value is detected: If the difference between this value and the previous value is A, then this value is invalid and given up. This value, replace this value with the last value

B. Advantages: It can effectively overcome pulse interference caused by accidental factors. Disadvantages: Unable to suppress periodic interference and poor smoothness.

C. Scope of application: measured values ​​that change slowly

2. Median filtering method

The median filter is a typical nonlinear filter. It has a simple operation and can well protect the detailed information of the signal while filtering out impulse noise.

A. Method: Continuously sample N times (N is an odd number), arrange the N sampled values ​​according to size (bubble method is often used), and take the middle value as the effective value this time.

B. Advantages: It can effectively overcome fluctuation (pulse) interference caused by accidental factors. Disadvantages: Not suitable for rapidly changing parameters such as flow rate and speed.

C. Scope of application: It has good filtering effect on measured parameters that change slowly in temperature and liquid level.

(2) Average filtering method to suppress small-amplitude high-frequency noise

Small-amplitude high-frequency electronic noise: electronic device thermal noise, A/D quantization noise, etc. Linear filters with low-pass characteristics are usually used: arithmetic average filtering method, weighted average filtering method, sliding weighted average filtering method, first-order lag filtering method, etc.

3. Arithmetic average filtering method The arithmetic average filtering method is to add N consecutive sampling values, and then take the arithmetic average as the filtered value of this measurement.

A. Method: Continuously take N sample values ​​and perform arithmetic average calculation. When the N value is larger: the signal smoothness is higher, but the sensitivity is lower. When the N value is smaller: the signal smoothness is lower, but the sensitivity is higher. Selection of the N value: General flow rate, N=12; pressure: N=4

B. Advantages: It is very effective in filtering out random interference signals mixed in the measured signal. The characteristic of the measured signal is that it has an average value, and the signal fluctuates up and down around a certain value range. Disadvantages: It is not easy to eliminate errors caused by pulse interference. For real-time systems that have slow sampling speeds or require high data update rates, the arithmetic mean filtering method cannot be used. A waste of RAM

4. Recursive average filtering method (also known as moving average filtering method)

For real-time systems that have slow sampling speeds or require high data update rates, the arithmetic mean filtering method cannot be used. The moving average filter method treats N measurement data as a queue. The length of the queue is fixed at N. Every time a new sampling is performed, the measurement result is placed at the end of the queue and the data at the head of the original queue is removed, so that it is always in the queue. There are N "latest" data.

A. Method: Treat N consecutive sampling values ​​as a queue. The length of the queue is fixed at N. Each time a new data is sampled, it is put into the end of the queue, and the original data at the head of the queue is thrown away. (First in, first out principle ) Perform an arithmetic average operation on the N data in the queue to obtain a new filtering result. Selection of N values: flow rate, N=12; pressure: N=4; liquid level, N=4 12; temperature, N= 1 4

B. Advantages: It has a good suppression effect on periodic interference, high smoothness and is suitable for high-frequency oscillation systems. Disadvantages: low sensitivity, poor suppression of occasional pulse interference, difficult to eliminate sampling value deviation caused by pulse interference, not suitable for occasions with serious pulse interference, waste of RAM

5. Weighted recursive average filtering method

A. Method: It is an improvement on the recursive average filtering method, that is, different weights are assigned to data at different times. Usually, the closer to the data at the current time, the greater the weight. The greater the weight coefficient given to the new sample value, the higher the sensitivity, but the smoothness of the signal is low.

B. Advantages: It is suitable for objects with large pure delay time constants and systems with short sampling periods. Disadvantages: For the pure lag time constant is small, the sampling period is long, the slow-changing signal cannot quickly reflect the severity of the current interference of the system, and the filtering effect is poor

6. First-order lag filtering method The first-order low-pass digital filter uses software to implement hardware RC filtering to suppress interference signals. In analog input channels, first-order lag RC analog filters are commonly used to suppress interference.

When using this method to achieve low-frequency interference, the first problem encountered is that the filter is required to have a large time constant (time constant = RC) and a high-precision RC network. The larger the time constant, the larger the RC value required, and the leakage current will inevitably increase, thus reducing the accuracy of the RC network. The digital filtering method with first-order lag can well overcome the shortcomings of this analog filter. This method is more suitable when the filter constant requirements are large.

A. Method: a=Tf/(Tf+T)Tf is the filtering time constant. T is the sampling period. This filtering result = (1-a) this sampling value + a last filtering result.

B. Advantages: It has good suppression effect on periodic interference and is suitable for occasions with high fluctuation frequency. Disadvantages: Phase lag, low sensitivity. The degree of lag depends on the value of a. Interfering signals with a filtering frequency higher than 1/2 of the sampling frequency cannot be eliminated.

(3) Composite filtering method

In practical applications, sometimes it is necessary to eliminate large-scale pulse interference and achieve data smoothing. Therefore, two or more methods introduced previously are often used in combination to form composite filtering. De-extreme average filtering algorithm: First use the median filter algorithm to filter out the impulsive interference in the sampled values, and then average the remaining sampled values. Continuously sample N times, eliminate the maximum and minimum values, and then find the average of the remaining N-2 samples. Obviously, this method can suppress random interference and filter out obvious pulse interference.

7. Median average filtering method (also known as anti-pulse interference average filtering method)

The median average filter method is equivalent to the "median value filter method" + "arithmetic average filter method".

A. Method: Continuously sample N data, remove a maximum value and a minimum value, and then calculate the arithmetic mean of N-2 data. Selection of N value: 3~14

B. Advantages: It combines the advantages of two filtering methods. This method can not only suppress random interference, but also filter out obvious pulse interference. Disadvantages: The measurement speed is slow, and like the arithmetic mean filtering method, it wastes RAM.

8. Limiting average filtering method

In situations where pulse interference is severe, if the general average method is used, the interference will be averaged into the result. Limiting average filtering method is equivalent to "limiting filtering method" + "recursive average filtering method"

A. Method: Each new sampled data is first subjected to limiting processing, and then sent to the queue for recursive average filtering processing.

B. Advantages: It combines the advantages of the two filtering methods. For the occasional pulse interference, the sampling value deviation caused by the pulse interference can be eliminated. Disadvantages: a waste of RAM

C. Scope of application: slowly changing signal

1. Limiting filter method (also known as program judgment filter method)

/*
A、名称:限幅滤波法(又称程序判断滤波法)
B、方法:
    根据经验判断,确定两次采样允许的最大偏差值(设为A),
    每次检测到新值时判断:
    如果本次值与上次值之差<=A,则本次值有效,
    如果本次值与上次值之差>A,则本次值无效,放弃本次值,用上次值代替本次值。
C、优点:
    能有效克服因偶然因素引起的脉冲干扰。
D、缺点:
    无法抑制那种周期性的干扰。
    平滑度差。
E、整理:shenhaiyu 2013-11-01
*/

int Filter_Value;
int Value;

void setup() {
  Serial.begin(9600);       // 初始化串口通信
  randomSeed(analogRead(0)); // 产生随机种子
  Value = 300;
}

void loop() {
  Filter_Value = Filter();       // 获得滤波器输出值
  Value = Filter_Value;          // 最近一次有效采样的值,该变量为全局变量
  Serial.println(Filter_Value); // 串口输出
  delay(50);
}

// 用于随机产生一个300左右的当前值
int Get_AD() {
  return random(295, 305);
}

// 限幅滤波法(又称程序判断滤波法)
#define FILTER_A 1
int Filter() {
  int NewValue;
  NewValue = Get_AD();
  if(((NewValue - Value) > FILTER_A) || ((Value - NewValue) > FILTER_A))
    return Value;
  else
    return NewValue;
}

/*
A、名称:限幅滤波法(又称程序判断滤波法)
B、方法:
    根据经验判断,确定两次采样允许的最大偏差值(设为A),
    每次检测到新值时判断:
    如果本次值与上次值之差<=A,则本次值有效,
    如果本次值与上次值之差>A,则本次值无效,放弃本次值,用上次值代替本次值。
C、优点:
    能有效克服因偶然因素引起的脉冲干扰。
D、缺点:
    无法抑制那种周期性的干扰。
    平滑度差。
E、整理:shenhaiyu 2013-11-01
*/

int Filter_Value;
int Value;

void setup() {
  Serial.begin(9600);       // 初始化串口通信
  randomSeed(analogRead(0)); // 产生随机种子
  Value = 300;
}

void loop() {
  Filter_Value = Filter();       // 获得滤波器输出值
  Value = Filter_Value;          // 最近一次有效采样的值,该变量为全局变量
  Serial.println(Filter_Value); // 串口输出
  delay(50);
}

// 用于随机产生一个300左右的当前值
int Get_AD() {
  return random(295, 305);
}

// 限幅滤波法(又称程序判断滤波法)
#define FILTER_A 1
int Filter() {
  int NewValue;
  NewValue = Get_AD();
  if(((NewValue - Value) > FILTER_A) || ((Value - NewValue) > FILTER_A))
    return Value;
  else
    return NewValue;
}

2. Median filtering method

/*
A、名称:中位值滤波法
B、方法:
    连续采样N次(N取奇数),把N次采样值按大小排列,
    取中间值为本次有效值。
C、优点:
    能有效克服因偶然因素引起的波动干扰;
    对温度、液位的变化缓慢的被测参数有良好的滤波效果。
D、缺点:
    对流量、速度等快速变化的参数不宜。
E、整理:shenhaiyu 2013-11-01
*/

int Filter_Value;

void setup() {
  Serial.begin(9600);       // 初始化串口通信
  randomSeed(analogRead(0)); // 产生随机种子
}

void loop() {
  Filter_Value = Filter();       // 获得滤波器输出值
  Serial.println(Filter_Value); // 串口输出
  delay(50);
}

// 用于随机产生一个300左右的当前值
int Get_AD() {
  return random(295, 305);
}

// 中位值滤波法
#define FILTER_N 101
int Filter() {
  int filter_buf[FILTER_N];
  int i, j;
  int filter_temp;
  for(i = 0; i < FILTER_N; i++) {
    filter_buf[i] = Get_AD();
    delay(1);
  }
  // 采样值从小到大排列(冒泡法)
  for(j = 0; j < FILTER_N - 1; j++) {
    for(i = 0; i < FILTER_N - 1 - j; i++) {
      if(filter_buf[i] > filter_buf[i + 1]) {
        filter_temp = filter_buf[i];
        filter_buf[i] = filter_buf[i + 1];
        filter_buf[i + 1] = filter_temp;
      }
    }
  }
  return filter_buf[(FILTER_N - 1) / 2];
}

3. Arithmetic mean filtering method

/*
A、名称:算术平均滤波法
B、方法:
    连续取N个采样值进行算术平均运算:
    N值较大时:信号平滑度较高,但灵敏度较低;
    N值较小时:信号平滑度较低,但灵敏度较高;
    N值的选取:一般流量,N=12;压力:N=4。
C、优点:
    适用于对一般具有随机干扰的信号进行滤波;
    这种信号的特点是有一个平均值,信号在某一数值范围附近上下波动。
D、缺点:
    对于测量速度较慢或要求数据计算速度较快的实时控制不适用;
    比较浪费RAM。
E、整理:shenhaiyu 2013-11-01
*/

int Filter_Value;

void setup() {
  Serial.begin(9600);       // 初始化串口通信
  randomSeed(analogRead(0)); // 产生随机种子
}

void loop() {
  Filter_Value = Filter();       // 获得滤波器输出值
  Serial.println(Filter_Value); // 串口输出
  delay(50);
}

// 用于随机产生一个300左右的当前值
int Get_AD() {
  return random(295, 305);
}

// 算术平均滤波法
#define FILTER_N 12
int Filter() {
  int i;
  int filter_sum = 0;
  for(i = 0; i < FILTER_N; i++) {
    filter_sum += Get_AD();
    delay(1);
  }
  return (int)(filter_sum / FILTER_N);
}
/*
A、名称:算术平均滤波法
B、方法:
    连续取N个采样值进行算术平均运算:
    N值较大时:信号平滑度较高,但灵敏度较低;
    N值较小时:信号平滑度较低,但灵敏度较高;
    N值的选取:一般流量,N=12;压力:N=4。
C、优点:
    适用于对一般具有随机干扰的信号进行滤波;
    这种信号的特点是有一个平均值,信号在某一数值范围附近上下波动。
D、缺点:
    对于测量速度较慢或要求数据计算速度较快的实时控制不适用;
    比较浪费RAM。
E、整理:shenhaiyu 2013-11-01
*/

int Filter_Value;

void setup() {
  Serial.begin(9600);       // 初始化串口通信
  randomSeed(analogRead(0)); // 产生随机种子
}

void loop() {
  Filter_Value = Filter();       // 获得滤波器输出值
  Serial.println(Filter_Value); // 串口输出
  delay(50);
}

// 用于随机产生一个300左右的当前值
int Get_AD() {
  return random(295, 305);
}

// 算术平均滤波法
#define FILTER_N 12
int Filter() {
  int i;
  int filter_sum = 0;
  for(i = 0; i < FILTER_N; i++) {
    filter_sum += Get_AD();
    delay(1);
  }
  return (int)(filter_sum / FILTER_N);
}

4. Recursive average filtering method (also known as moving average filtering method)

/*
A、名称:递推平均滤波法(又称滑动平均滤波法)
B、方法:
    把连续取得的N个采样值看成一个队列,队列的长度固定为N,
    每次采样到一个新数据放入队尾,并扔掉原来队首的一次数据(先进先出原则),
    把队列中的N个数据进行算术平均运算,获得新的滤波结果。
    N值的选取:流量,N=12;压力,N=4;液面,N=4-12;温度,N=1-4。
C、优点:
    对周期性干扰有良好的抑制作用,平滑度高;
    适用于高频振荡的系统。
D、缺点:
    灵敏度低,对偶然出现的脉冲性干扰的抑制作用较差;
    不易消除由于脉冲干扰所引起的采样值偏差;
    不适用于脉冲干扰比较严重的场合;
    比较浪费RAM。
E、整理:shenhaiyu 2013-11-01
*/

int Filter_Value;

void setup() {
  Serial.begin(9600);       // 初始化串口通信
  randomSeed(analogRead(0)); // 产生随机种子
}

void loop() {
  Filter_Value = Filter();       // 获得滤波器输出值
  Serial.println(Filter_Value); // 串口输出
  delay(50);
}

// 用于随机产生一个300左右的当前值
int Get_AD() {
  return random(295, 305);
}

// 递推平均滤波法(又称滑动平均滤波法)
#define FILTER_N 12
int filter_buf[FILTER_N + 1];
int Filter() {
  int i;
  int filter_sum = 0;
  filter_buf[FILTER_N] = Get_AD();
  for(i = 0; i < FILTER_N; i++) {
    filter_buf[i] = filter_buf[i + 1]; // 所有数据左移,低位仍掉
    filter_sum += filter_buf[i];
  }
  return (int)(filter_sum / FILTER_N);
}
/*
A、名称:递推平均滤波法(又称滑动平均滤波法)
B、方法:
    把连续取得的N个采样值看成一个队列,队列的长度固定为N,
    每次采样到一个新数据放入队尾,并扔掉原来队首的一次数据(先进先出原则),
    把队列中的N个数据进行算术平均运算,获得新的滤波结果。
    N值的选取:流量,N=12;压力,N=4;液面,N=4-12;温度,N=1-4。
C、优点:
    对周期性干扰有良好的抑制作用,平滑度高;
    适用于高频振荡的系统。
D、缺点:
    灵敏度低,对偶然出现的脉冲性干扰的抑制作用较差;
    不易消除由于脉冲干扰所引起的采样值偏差;
    不适用于脉冲干扰比较严重的场合;
    比较浪费RAM。
E、整理:shenhaiyu 2013-11-01
*/

int Filter_Value;

void setup() {
  Serial.begin(9600);       // 初始化串口通信
  randomSeed(analogRead(0)); // 产生随机种子
}

void loop() {
  Filter_Value = Filter();       // 获得滤波器输出值
  Serial.println(Filter_Value); // 串口输出
  delay(50);
}

// 用于随机产生一个300左右的当前值
int Get_AD() {
  return random(295, 305);
}

// 递推平均滤波法(又称滑动平均滤波法)
#define FILTER_N 12
int filter_buf[FILTER_N + 1];
int Filter() {
  int i;
  int filter_sum = 0;
  filter_buf[FILTER_N] = Get_AD();
  for(i = 0; i < FILTER_N; i++) {
    filter_buf[i] = filter_buf[i + 1]; // 所有数据左移,低位仍掉
    filter_sum += filter_buf[i];
  }
  return (int)(filter_sum / FILTER_N);
}

5. Median average filtering method (also known as anti-pulse interference average filtering method)

/*
A、名称:中位值平均滤波法(又称防脉冲干扰平均滤波法)
B、方法:
    采一组队列去掉最大值和最小值后取平均值,
    相当于“中位值滤波法”+“算术平均滤波法”。
    连续采样N个数据,去掉一个最大值和一个最小值,
    然后计算N-2个数据的算术平均值。
    N值的选取:3-14。
C、优点:
    融合了“中位值滤波法”+“算术平均滤波法”两种滤波法的优点。
    对于偶然出现的脉冲性干扰,可消除由其所引起的采样值偏差。
    对周期干扰有良好的抑制作用。
    平滑度高,适于高频振荡的系统。
D、缺点:
    计算速度较慢,和算术平均滤波法一样。
    比较浪费RAM。
E、整理:shenhaiyu 2013-11-01
*/

int Filter_Value;

void setup() {
  Serial.begin(9600);       // 初始化串口通信
  randomSeed(analogRead(0)); // 产生随机种子
}

void loop() {
  Filter_Value = Filter();       // 获得滤波器输出值
  Serial.println(Filter_Value); // 串口输出
  delay(50);
}

// 用于随机产生一个300左右的当前值
int Get_AD() {
  return random(295, 305);
}

// 中位值平均滤波法(又称防脉冲干扰平均滤波法)(算法1)
#define FILTER_N 100
int Filter() {
  int i, j;
  int filter_temp, filter_sum = 0;
  int filter_buf[FILTER_N];
  for(i = 0; i < FILTER_N; i++) {
    filter_buf[i] = Get_AD();
    delay(1);
  }
  // 采样值从小到大排列(冒泡法)
  for(j = 0; j < FILTER_N - 1; j++) {
    for(i = 0; i < FILTER_N - 1 - j; i++) {
      if(filter_buf[i] > filter_buf[i + 1]) {
        filter_temp = filter_buf[i];
        filter_buf[i] = filter_buf[i + 1];
        filter_buf[i + 1] = filter_temp;
      }
    }
  }
  // 去除最大最小极值后求平均
  for(i = 1; i < FILTER_N - 1; i++) filter_sum += filter_buf[i];
  return filter_sum / (FILTER_N - 2);
}


//  中位值平均滤波法(又称防脉冲干扰平均滤波法)(算法2)
/*
#define FILTER_N 100
int Filter() {
  int i;
  int filter_sum = 0;
  int filter_max, filter_min;
  int filter_buf[FILTER_N];
  for(i = 0; i < FILTER_N; i++) {
    filter_buf[i] = Get_AD();
    delay(1);
  }
  filter_max = filter_buf[0];
  filter_min = filter_buf[0];
  filter_sum = filter_buf[0];
  for(i = FILTER_N - 1; i > 0; i--) {
    if(filter_buf[i] > filter_max)
      filter_max=filter_buf[i];
    else if(filter_buf[i] < filter_min)
      filter_min=filter_buf[i];
    filter_sum = filter_sum + filter_buf[i];
    filter_buf[i] = filter_buf[i - 1];
  }
  i = FILTER_N - 2;
  filter_sum = filter_sum - filter_max - filter_min + i / 2; // +i/2 的目的是为了四舍五入
  filter_sum = filter_sum / i;
  return filter_sum;
}*/
/*
A、名称:中位值平均滤波法(又称防脉冲干扰平均滤波法)
B、方法:
    采一组队列去掉最大值和最小值后取平均值,
    相当于“中位值滤波法”+“算术平均滤波法”。
    连续采样N个数据,去掉一个最大值和一个最小值,
    然后计算N-2个数据的算术平均值。
    N值的选取:3-14。
C、优点:
    融合了“中位值滤波法”+“算术平均滤波法”两种滤波法的优点。
    对于偶然出现的脉冲性干扰,可消除由其所引起的采样值偏差。
    对周期干扰有良好的抑制作用。
    平滑度高,适于高频振荡的系统。
D、缺点:
    计算速度较慢,和算术平均滤波法一样。
    比较浪费RAM。
E、整理:shenhaiyu 2013-11-01
*/

int Filter_Value;

void setup() {
  Serial.begin(9600);       // 初始化串口通信
  randomSeed(analogRead(0)); // 产生随机种子
}

void loop() {
  Filter_Value = Filter();       // 获得滤波器输出值
  Serial.println(Filter_Value); // 串口输出
  delay(50);
}

// 用于随机产生一个300左右的当前值
int Get_AD() {
  return random(295, 305);
}

// 中位值平均滤波法(又称防脉冲干扰平均滤波法)(算法1)
#define FILTER_N 100
int Filter() {
  int i, j;
  int filter_temp, filter_sum = 0;
  int filter_buf[FILTER_N];
  for(i = 0; i < FILTER_N; i++) {
    filter_buf[i] = Get_AD();
    delay(1);
  }
  // 采样值从小到大排列(冒泡法)
  for(j = 0; j < FILTER_N - 1; j++) {
    for(i = 0; i < FILTER_N - 1 - j; i++) {
      if(filter_buf[i] > filter_buf[i + 1]) {
        filter_temp = filter_buf[i];
        filter_buf[i] = filter_buf[i + 1];
        filter_buf[i + 1] = filter_temp;
      }
    }
  }
  // 去除最大最小极值后求平均
  for(i = 1; i < FILTER_N - 1; i++) filter_sum += filter_buf[i];
  return filter_sum / (FILTER_N - 2);
}


//  中位值平均滤波法(又称防脉冲干扰平均滤波法)(算法2)
/*
#define FILTER_N 100
int Filter() {
  int i;
  int filter_sum = 0;
  int filter_max, filter_min;
  int filter_buf[FILTER_N];
  for(i = 0; i < FILTER_N; i++) {
    filter_buf[i] = Get_AD();
    delay(1);
  }
  filter_max = filter_buf[0];
  filter_min = filter_buf[0];
  filter_sum = filter_buf[0];
  for(i = FILTER_N - 1; i > 0; i--) {
    if(filter_buf[i] > filter_max)
      filter_max=filter_buf[i];
    else if(filter_buf[i] < filter_min)
      filter_min=filter_buf[i];
    filter_sum = filter_sum + filter_buf[i];
    filter_buf[i] = filter_buf[i - 1];
  }
  i = FILTER_N - 2;
  filter_sum = filter_sum - filter_max - filter_min + i / 2; // +i/2 的目的是为了四舍五入
  filter_sum = filter_sum / i;
  return filter_sum;
}*/

6. Limiting average filtering method

/*
A、名称:限幅平均滤波法
B、方法:
    相当于“限幅滤波法”+“递推平均滤波法”;
    每次采样到的新数据先进行限幅处理,
    再送入队列进行递推平均滤波处理。
C、优点:
    融合了两种滤波法的优点;
    对于偶然出现的脉冲性干扰,可消除由于脉冲干扰所引起的采样值偏差。
D、缺点:
    比较浪费RAM。
E、整理:shenhaiyu 2013-11-01
*/

#define FILTER_N 12
int Filter_Value;
int filter_buf[FILTER_N];

void setup() {
  Serial.begin(9600);       // 初始化串口通信
  randomSeed(analogRead(0)); // 产生随机种子
  filter_buf[FILTER_N - 2] = 300;
}

void loop() {
  Filter_Value = Filter();       // 获得滤波器输出值
  Serial.println(Filter_Value); // 串口输出
  delay(50);
}

// 用于随机产生一个300左右的当前值
int Get_AD() {
  return random(295, 305);
}

// 限幅平均滤波法
#define FILTER_A 1
int Filter() {
  int i;
  int filter_sum = 0;
  filter_buf[FILTER_N - 1] = Get_AD();
  if(((filter_buf[FILTER_N - 1] - filter_buf[FILTER_N - 2]) > FILTER_A) || ((filter_buf[FILTER_N - 2] - filter_buf[FILTER_N - 1]) > FILTER_A))
    filter_buf[FILTER_N - 1] = filter_buf[FILTER_N - 2];
  for(i = 0; i < FILTER_N - 1; i++) {
    filter_buf[i] = filter_buf[i + 1];
    filter_sum += filter_buf[i];
  }
  return (int)filter_sum / (FILTER_N - 1);
}

7. First-order lag filtering method

/*
A、名称:一阶滞后滤波法
B、方法:
    取a=0-1,本次滤波结果=(1-a)*本次采样值+a*上次滤波结果。
C、优点:
    对周期性干扰具有良好的抑制作用;
    适用于波动频率较高的场合。
D、缺点:
    相位滞后,灵敏度低;
    滞后程度取决于a值大小;
    不能消除滤波频率高于采样频率1/2的干扰信号。
E、整理:shenhaiyu 2013-11-01
*/

int Filter_Value;
int Value;

void setup() {
  Serial.begin(9600);       // 初始化串口通信
  randomSeed(analogRead(0)); // 产生随机种子
  Value = 300;
}

void loop() {
  Filter_Value = Filter();       // 获得滤波器输出值
  Serial.println(Filter_Value); // 串口输出
  delay(50);
}

// 用于随机产生一个300左右的当前值
int Get_AD() {
  return random(295, 305);
}

// 一阶滞后滤波法
#define FILTER_A 0.01
int Filter() {
  int NewValue;
  NewValue = Get_AD();
  Value = (int)((float)NewValue * FILTER_A + (1.0 - FILTER_A) * (float)Value);
  return Value;
}

8. Weighted recursive average filtering method

/*
A、名称:加权递推平均滤波法
B、方法:
    是对递推平均滤波法的改进,即不同时刻的数据加以不同的权;
    通常是,越接近现时刻的数据,权取得越大。
    给予新采样值的权系数越大,则灵敏度越高,但信号平滑度越低。
C、优点:
    适用于有较大纯滞后时间常数的对象,和采样周期较短的系统。
D、缺点:
    对于纯滞后时间常数较小、采样周期较长、变化缓慢的信号;
    不能迅速反应系统当前所受干扰的严重程度,滤波效果差。
E、整理:shenhaiyu 2013-11-01
*/

int Filter_Value;

void setup() {
  Serial.begin(9600);       // 初始化串口通信
  randomSeed(analogRead(0)); // 产生随机种子
}

void loop() {
  Filter_Value = Filter();       // 获得滤波器输出值
  Serial.println(Filter_Value); // 串口输出
  delay(50);
}

// 用于随机产生一个300左右的当前值
int Get_AD() {
  return random(295, 305);
}

// 加权递推平均滤波法
#define FILTER_N 12
int coe[FILTER_N] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};    // 加权系数表
int sum_coe = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12; // 加权系数和
int filter_buf[FILTER_N + 1];
int Filter() {
  int i;
  int filter_sum = 0;
  filter_buf[FILTER_N] = Get_AD();
  for(i = 0; i < FILTER_N; i++) {
    filter_buf[i] = filter_buf[i + 1]; // 所有数据左移,低位仍掉
    filter_sum += filter_buf[i] * coe[i];
  }
  filter_sum /= sum_coe;
  return filter_sum;
}

9. Anti-bounce filtering method

/*
A、名称:消抖滤波法
B、方法:
    设置一个滤波计数器,将每次采样值与当前有效值比较:
    如果采样值=当前有效值,则计数器清零;
    如果采样值<>当前有效值,则计数器+1,并判断计数器是否>=上限N(溢出);
    如果计数器溢出,则将本次值替换当前有效值,并清计数器。
C、优点:
    对于变化缓慢的被测参数有较好的滤波效果;
    可避免在临界值附近控制器的反复开/关跳动或显示器上数值抖动。
D、缺点:
    对于快速变化的参数不宜;
    如果在计数器溢出的那一次采样到的值恰好是干扰值,则会将干扰值当作有效值导入系统。
E、整理:shenhaiyu 2013-11-01
*/

int Filter_Value;
int Value;

void setup() {
  Serial.begin(9600);       // 初始化串口通信
  randomSeed(analogRead(0)); // 产生随机种子
  Value = 300;
}

void loop() {
  Filter_Value = Filter();       // 获得滤波器输出值
  Serial.println(Filter_Value); // 串口输出
  delay(50);
}

// 用于随机产生一个300左右的当前值
int Get_AD() {
  return random(295, 305);
}

// 消抖滤波法
#define FILTER_N 12
int i = 0;
int Filter() {
  int new_value;
  new_value = Get_AD();
  if(Value != new_value) {
    i++;
    if(i > FILTER_N) {
      i = 0;
      Value = new_value;
    }
  }
  else
    i = 0;
  return Value;
}

10. Limiting debounce filtering method

/*
A、名称:限幅消抖滤波法
B、方法:
    相当于“限幅滤波法”+“消抖滤波法”;
    先限幅,后消抖。
C、优点:
    继承了“限幅”和“消抖”的优点;
    改进了“消抖滤波法”中的某些缺陷,避免将干扰值导入系统。
D、缺点:
    对于快速变化的参数不宜。
E、整理:shenhaiyu 2013-11-01
*/

int Filter_Value;
int Value;

void setup() {
  Serial.begin(9600);       // 初始化串口通信
  randomSeed(analogRead(0)); // 产生随机种子
  Value = 300;
}

void loop() {
  Filter_Value = Filter();       // 获得滤波器输出值
  Serial.println(Filter_Value); // 串口输出
  delay(50);
}

// 用于随机产生一个300左右的当前值
int Get_AD() {
  return random(295, 305);
}

// 限幅消抖滤波法
#define FILTER_A 1
#define FILTER_N 5
int i = 0;
int Filter() {
  int NewValue;
  int new_value;
  NewValue = Get_AD();
  if(((NewValue - Value) > FILTER_A) || ((Value - NewValue) > FILTER_A))
    new_value = Value;
  else
    new_value = NewValue;
  if(Value != new_value) {
    i++;
    if(i > FILTER_N) {
      i = 0;
      Value = new_value;
    }
  }
  else
    i = 0;
  return Value;
}

11. Kalman filter (non-extended Kalman)

#include <Wire.h> // I2C library, gyroscope

// Accelerometer ADXL345
#define ACC (0x53)    //ADXL345 ACC address
#define A_TO_READ (6)        //num of bytes we are going to read each time (two bytes for each axis)


// Gyroscope ITG3200 
#define GYRO 0x68 // gyro address, binary = 11101000 when AD0 is connected to Vcc (see schematics of your breakout board)
#define G_SMPLRT_DIV 0x15   
#define G_DLPF_FS 0x16   
#define G_INT_CFG 0x17
#define G_PWR_MGM 0x3E

#define G_TO_READ 8 // 2 bytes for each axis x, y, z


// offsets are chip specific. 
int a_offx = 0;
int a_offy = 0;
int a_offz = 0;

int g_offx = 0;
int g_offy = 0;
int g_offz = 0;



char str[512]; 

void initAcc() {
  //Turning on the ADXL345
  writeTo(ACC, 0x2D, 0);      
  writeTo(ACC, 0x2D, 16);
  writeTo(ACC, 0x2D, 8);
  //by default the device is in +-2g range reading
}

void getAccelerometerData(int* result) {
  int regAddress = 0x32;    //first axis-acceleration-data register on the ADXL345
  byte buff[A_TO_READ];
  
  readFrom(ACC, regAddress, A_TO_READ, buff); //read the acceleration data from the ADXL345
  
  //each axis reading comes in 10 bit resolution, ie 2 bytes.  Least Significat Byte first!!
  //thus we are converting both bytes in to one int
  result[0] = (((int)buff[1]) << 8) | buff[0] + a_offx;   
  result[1] = (((int)buff[3]) << 8) | buff[2] + a_offy;
  result[2] = (((int)buff[5]) << 8) | buff[4] + a_offz;
}

//initializes the gyroscope
void initGyro()
{
  /*****************************************
  * ITG 3200
  * power management set to:
  * clock select = internal oscillator
  *     no reset, no sleep mode
  *   no standby mode
  * sample rate to = 125Hz
  * parameter to +/- 2000 degrees/sec
  * low pass filter = 5Hz
  * no interrupt
  ******************************************/
  writeTo(GYRO, G_PWR_MGM, 0x00);
  writeTo(GYRO, G_SMPLRT_DIV, 0x07); // EB, 50, 80, 7F, DE, 23, 20, FF
  writeTo(GYRO, G_DLPF_FS, 0x1E); // +/- 2000 dgrs/sec, 1KHz, 1E, 19
  writeTo(GYRO, G_INT_CFG, 0x00);
}


void getGyroscopeData(int * result)
{
  /**************************************
  Gyro ITG-3200 I2C
  registers:
  temp MSB = 1B, temp LSB = 1C
  x axis MSB = 1D, x axis LSB = 1E
  y axis MSB = 1F, y axis LSB = 20
  z axis MSB = 21, z axis LSB = 22
  *************************************/

  int regAddress = 0x1B;
  int temp, x, y, z;
  byte buff[G_TO_READ];
  
  readFrom(GYRO, regAddress, G_TO_READ, buff); //read the gyro data from the ITG3200
  
  result[0] = ((buff[2] << 8) | buff[3]) + g_offx;
  result[1] = ((buff[4] << 8) | buff[5]) + g_offy;
  result[2] = ((buff[6] << 8) | buff[7]) + g_offz;
  result[3] = (buff[0] << 8) | buff[1]; // temperature
  
}


float xz=0,yx=0,yz=0;
float p_xz=1,p_yx=1,p_yz=1;
float q_xz=0.0025,q_yx=0.0025,q_yz=0.0025;
float k_xz=0,k_yx=0,k_yz=0;
float r_xz=0.25,r_yx=0.25,r_yz=0.25;
  //int acc_temp[3];
  //float acc[3];
  int acc[3];
  int gyro[4];
  float Axz;
  float Ayx;
  float Ayz;
  float t=0.025;
void setup()
{
  Serial.begin(9600);
  Wire.begin();
  initAcc();
  initGyro();
  
}

//unsigned long timer = 0;
//float o;
void loop()
{
  
  getAccelerometerData(acc);
  getGyroscopeData(gyro);
  //timer = millis();
  sprintf(str, "%d,%d,%d,%d,%d,%d", acc[0],acc[1],acc[2],gyro[0],gyro[1],gyro[2]);
  
  //acc[0]=acc[0];
  //acc[2]=acc[2];
  //acc[1]=acc[1];
  //r=sqrt(acc[0]*acc[0]+acc[1]*acc[1]+acc[2]*acc[2]);
  gyro[0]=gyro[0]/ 14.375;
  gyro[1]=gyro[1]/ (-14.375);
  gyro[2]=gyro[2]/ 14.375;
  
   
  Axz=(atan2(acc[0],acc[2]))*180/PI;
  Ayx=(atan2(acc[0],acc[1]))*180/PI;
  /*if((acc[0]!=0)&&(acc[1]!=0))
    {
      Ayx=(atan2(acc[0],acc[1]))*180/PI;
    }
    else
    {
      Ayx=t*gyro[2];
    }*/
  Ayz=(atan2(acc[1],acc[2]))*180/PI;
  
  
 //kalman filter
  calculate_xz();
  calculate_yx();
  calculate_yz();
  
  //sprintf(str, "%d,%d,%d", xz_1, xy_1, x_1);
  //Serial.print(xz);Serial.print(",");
  //Serial.print(yx);Serial.print(",");
  //Serial.print(yz);Serial.print(",");
  //sprintf(str, "%d,%d,%d,%d,%d,%d", acc[0],acc[1],acc[2],gyro[0],gyro[1],gyro[2]);
  //sprintf(str, "%d,%d,%d",gyro[0],gyro[1],gyro[2]);
    Serial.print(Axz);Serial.print(",");
    //Serial.print(Ayx);Serial.print(",");
    //Serial.print(Ayz);Serial.print(",");
  //Serial.print(str);
  //o=gyro[2];//w=acc[2];
  //Serial.print(o);Serial.print(",");
  //Serial.print(w);Serial.print(",");
  Serial.print("\n");

  
  //delay(50);
}
void calculate_xz()
{

 xz=xz+t*gyro[1];
 p_xz=p_xz+q_xz;
 k_xz=p_xz/(p_xz+r_xz);
 xz=xz+k_xz*(Axz-xz);
 p_xz=(1-k_xz)*p_xz;
}
void calculate_yx()
{
  
  yx=yx+t*gyro[2];
  p_yx=p_yx+q_yx;
  k_yx=p_yx/(p_yx+r_yx);
  yx=yx+k_yx*(Ayx-yx);
  p_yx=(1-k_yx)*p_yx;

}
void calculate_yz()
{
  yz=yz+t*gyro[0];
  p_yz=p_yz+q_yz;
  k_yz=p_yz/(p_yz+r_yz);
  yz=yz+k_yz*(Ayz-yz);
  p_yz=(1-k_yz)*p_yz;
 
}


//---------------- Functions
//Writes val to address register on ACC
void writeTo(int DEVICE, byte address, byte val) {
   Wire.beginTransmission(DEVICE); //start transmission to ACC 
   Wire.write(address);        // send register address
   Wire.write(val);        // send value to write
   Wire.endTransmission(); //end transmission
}


//reads num bytes starting from address register on ACC in to buff array
void readFrom(int DEVICE, byte address, int num, byte buff[]) {
  Wire.beginTransmission(DEVICE); //start transmission to ACC 
  Wire.write(address);        //sends address to read from
  Wire.endTransmission(); //end transmission
  
  Wire.beginTransmission(DEVICE); //start transmission to ACC
  Wire.requestFrom(DEVICE, num);    // request 6 bytes from ACC
  
  int i = 0;
  while(Wire.available())    //ACC may send less than requested (abnormal)
  { 
    buff[i] = Wire.read(); // receive a byte
    i++;
  }
  Wire.endTransmission(); //end transmission
}

Guess you like

Origin blog.csdn.net/qq_41854911/article/details/132527163