Created
September 6, 2021 08:15
-
-
Save olegkapitonov/a063d286a25ded25916404394c308d0d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <stdio.h> | |
#include <math.h> | |
int fSampleRate; | |
// Filter parameters, set by init function | |
float a; | |
float b; | |
float c; | |
float d; | |
float e; | |
// 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 / pow(fc, 2); | |
c = (1.0 / fc - sqrt(2)) / fc + 1.0; | |
d = 2.0 * (1.0 - b); | |
e = - 2.0 / pow(fc, 2); | |
} | |
// 2-order hipass filter, | |
// input, output - data arrays | |
// count - number of samples to process | |
void highpass2(int count, float input[], float output[]) { | |
for (int i = 0; (i < count); i++) { | |
buf[0] = input[i] - a * (c * buf[2] + d * buf[1]); | |
output[i] = a * (b * buf[0] + e * buf[1] + b * buf[2]); | |
buf[2] = buf[1]; | |
buf[1] = buf[0]; | |
} | |
} | |
int main(void) { | |
FILE *fp; | |
fp = fopen("processed.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, 300.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 | |
highpass2(I_head, I, I_filtered); | |
highpass2(I_head, I_filtered, I_filtered); | |
highpass2(I_head, I_filtered, I_filtered); | |
highpass2(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