Skip to content

Instantly share code, notes, and snippets.

@mattiasgustavsson
Last active March 28, 2025 16:32
Show Gist options
  • Save mattiasgustavsson/3f56e6d0bcd7e581ad1f19d196cb1e7b to your computer and use it in GitHub Desktop.
Save mattiasgustavsson/3f56e6d0bcd7e581ad1f19d196cb1e7b to your computer and use it in GitHub Desktop.
low pass filter
typedef struct filter_t {
double a0, a1, a2; // Feedforward coefficients
double b1, b2; // Feedback coefficients
double z1, z2; // Filter state (history)
} filter_t;
void filter_init(filter_t *filter, double cutoff, double sample_rate) {
double const PI = 3.14159265358979323846;
double omega = 2.0 * PI * cutoff / sample_rate;
double sin_omega = sin( omega );
double cos_omega = cos( omega );
double alpha = sin_omega / sqrt( 2.0 ); // Q = 1 / sqrt( 2 ) (Butterworth)
double a0_inv = 1.0 / ( 1.0 + alpha );
filter->a0 = ( 1.0 - cos_omega ) / 2.0 * a0_inv;
filter->a1 = ( 1.0 - cos_omega ) * a0_inv;
filter->a2 = ( 1.0 - cos_omega ) / 2.0 * a0_inv;
filter->b1 = -2.0 * cos_omega * a0_inv;
filter->b2 = ( 1.0 - alpha ) * a0_inv;
filter->z1 = 0.0;
filter->z2 = 0.0;
}
double filter_apply(filter_t *filter, double input) {
double output = filter->a0 * input + filter->a1 * filter->z1 +
filter->a2 * filter->z2 - filter->b1 * filter->z1 - filter->b2 * filter->z2;
filter->z2 = filter->z1;
filter->z1 = output;
return output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment