I'd like to use a built-in function to apply a pass-band butterworth filter to gyro and accelerometer signals.
In the "base" version of my sketch I computed the transfer function coefficients through Matlab and imported in IDE and used a function to apply the filter to my signal.
IMU.readAcceleration(ax, ay, az);
filtered = butterworthBandpassFilter(az);
float butterworthBandpassFilter(float input) {
// Shift previous inputs and outputs
for (int i = 10; i > 0; i--) {
x[i] = x[i-1];
y[i] = y[i-1];
}
// Set the new input value
x[0] = input;
// Apply the filter equation: y[n] = sum(b[i]*x[n-i]) - sum(a[i]*y[n-i])
float output = 0;
for (int i = 0; i < 11; i++) {
output += b[i] * x[i];
if (i > 0) {
output -= a[i] * y[i];
}
}
// Store the output value
y[0] = output;
return output;
}
where, input is my raw signal, a and b the two vectors containing the filter coefficients, x and y two variables to support the computations (initialized to 0)
// Filter coefficients (from matlab script: 0.1-0.49 Hz)
float b[21] = {0.00931683037284933, 0, -0.0931683037284933, 0, 0.419257366778220, 0, -1.11801964474192, 0, 1.95653437829836, 0, -2.34784125395803, 0, 1.95653437829836, 0, -1.11801964474192, 0, 0.419257366778220, 0, -0.0931683037284933, 0, 0.00931683037284933};
float a[21] = {1, 7.70916073863389, 26.2193801260813, 52.9090893787506, 74.1857165778666, 83.2831166956718, 82.1591744709078, 69.9143748679608, 48.9193599755739, 29.4495226454652, 16.5180734695797, 7.91051329362060, 2.83326241996057, 0.956145139883915, 0.374057155228569, 0.0703549907427079, -0.00271358318385719, 0.00614164964651132, 0.00136790282939128, -0.000653542477654263, 8.73430659265187e-05};
// Filtered values (state variables)
float x[21] = {0}; // Input history
float y[21] = {0}; // Output history
The problem with this approach is that if I want to change the sampling or cutoff frequency, coefficients change and I need to calculate them first in Matlab, then copy-paste in the sketch.
I found this repository with functions to compute the the transfer function but I don't understand how to extract coefficients that I need.
The best would be find a function that works the same as Matlab's "butter" and "filter" or "filtfilt" functions. I found a function that says doing this job but it misses the .h file and I don't know how to write it to make it work or convert it to be usable in IDE.
Do you have any alternative/ideas to do this job?