Skip to content

Instantly share code, notes, and snippets.

@olegkapitonov
Created September 6, 2021 08:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olegkapitonov/feb58ec5a7f1816ec72678275facc07e to your computer and use it in GitHub Desktop.
Save olegkapitonov/feb58ec5a7f1816ec72678275facc07e to your computer and use it in GitHub Desktop.
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int fSampleRate;
// Filter parameters, set by init function
float a;
float b;
float c;
// Filter buffer
float buf[3];
// Calculate filter parameters,
// f - filter cutoff frequency, Hz
void init(int sample_rate, float f) {
fSampleRate = sample_rate;
float fc = tan(M_PI * f / (float)fSampleRate);
a = 1.0 / ((1.0 / fc + sqrt(2)) / fc + 1.0);
b = ((1.0 / fc - sqrt(2)) / fc) + 1.0f;
c = 2.0 * (1.0 - (1.0 / pow(fc, 2)));
}
// 2-order lowpass filter,
// input, output - data arrays
// count - number of samples to process
void lowpass2(int count, float input[], float output[]) {
for (int i = 0; (i < count); i++) {
buf[0] = input[i] - a * (b * buf[2] + c * buf[1]);
output[i] = a * (buf[0] + buf[2] + 2.0f * buf[1]);
buf[2] = buf[1];
buf[1] = buf[0];
}
}
int main(void) {
FILE *fp;
fp = fopen("filtered.txt", "r");
int r;
fseek(fp, 0, SEEK_END);
long fsize = ftell(fp);
fseek(fp, 0, SEEK_SET);
float* I = malloc(fsize * sizeof(float));
int I_head = 0;
// 250 kHz, cutoff frequency - 300 Hz
init(250000, 3000.0);
while(r != EOF ) {
int t;
r = fscanf(fp, "%d %f\n", &t, &I[I_head]);
I_head++;
}
float* I_filtered = malloc(I_head * sizeof(float));
// Order: 2+2+2+2 = 8
lowpass2(I_head, I, I_filtered);
lowpass2(I_head, I_filtered, I_filtered);
lowpass2(I_head, I_filtered, I_filtered);
lowpass2(I_head, I_filtered, I_filtered);
for (int i = 0; i < I_head; i++) {
printf("%d %f\n", (int)(1.0/fSampleRate*1000000.0*i), I_filtered[i]);
}
fclose(fp);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment