Embedded commonly used algorithm - first-order RC low-pass filter algorithm

The first-order RC low-pass filter algorithm is a circuit analog filter that eliminates noise by attenuating the signal of the high-frequency part. This type of filter consists of a resistor and a capacitor, so it is called an RC low-pass filter.

Specifically, a low-pass filter removes noise by attenuating the high-frequency portion of the signal. The signal in the high frequency part refers to the signal whose frequency is higher than the cutoff frequency, and the cutoff frequency refers to the frequency at which the attenuation of the high frequency part signal by the filter starts.

The input signal of the low-pass filter is transmitted to the capacitor through the resistor, and the capacitor will lag behind the resistor to cause signal attenuation. In a first-order RC low-pass filter, the cutoff frequency is determined by both the resistor and the capacitor. Specifically, the cutoff frequency fc = 1 / (2πRC).

The following is a code example of a first-order RC low-pass filter written in C language:

#include <stdio.h>
#define PI 3.14159265

float lowpass(float input, float output_prev, float RC, float dt) {
    
    
    float alpha = dt / (RC + dt);
    return output_prev + alpha * (input - output_prev);
}

int main() {
    
    
    float RC = 1 / (2 * PI * 1000);  // 1000 Hz cutoff frequency
    float dt = 1 / 44100;  // sample rate is 44.1 kHz
    float input = 0.5;  // input signal
    float output_prev = 0;  // previous output
    float output = lowpass(input, output_prev, RC, dt);
    printf("%f", output);
    return 0;
}

The code example defines a lowpass() function that accepts the input signal, the last output, the RC time constant, and the sampling interval as arguments. In the function, alpha is defined as dt / (RC + dt), which is used to calculate the new output value.

The new output value is calculated by multiplying the difference between the previous output and the input signal by alpha. This way, if the input signal is the same as the previous output, the new output will be the same as the previous output, otherwise the new output will be close to the input signal.

In the main() function, we set the cutoff frequency to 1000 Hz, the sampling rate to 44.1 kHz, and the input signal to 0.5. We call the lowpass() function, setting the previous output to 0. Finally, we print out the new output.

The first-order RC low-pass filtering algorithm is a simple and effective filtering method, which can effectively eliminate high-frequency noise. However, it should be noted that this filtering method sometimes affects the time-domain performance of the signal, so it needs to be weighed according to the specific application scenario.

Guess you like

Origin blog.csdn.net/sorcererr/article/details/128700931