Arduino Filters master
Filter library for Arduino
Butterworth.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <AH/STL/cmath>
5
8
25template <uint8_t N, class T = float>
26SOSCoefficients<T, (N + 1) / 2> butter_coeff(double f_n,
27 bool normalize = true) {
28 const double gamma = 1 / std::tan(M_PI * f_n / 2); // pre-warp factor
29
30 auto make_sos = [=](uint8_t k) {
31 const double gamma2 = gamma * gamma;
32 const double alpha = 2 * std::cos(2 * M_PI * (2 * k + N + 1) / (4 * N));
34 {{T(1.), T(2.), T(1.)}}, // b0, b1, b2
35 {{
36 T(gamma2 - alpha * gamma + 1), // a0
37 T(2 * (1 - gamma2)), // a1
38 T(gamma2 + alpha * gamma + 1), // a2
39 }},
40 };
41 };
42 auto make_fos = [=]() {
44 {{T(1.), T(1.)}}, // b0, b1
45 {{
46 T(gamma + 1), // a0
47 T(1 - gamma), // a1
48 }},
49 };
50 };
51
52 auto make_sos_norm = [=](uint8_t k) {
53 const double gamma2 = gamma * gamma;
54 const double alpha = 2 * std::cos(2 * M_PI * (2 * k + N + 1) / (4 * N));
55 const double a0 = gamma2 - alpha * gamma + 1;
57 {{T(1. / a0), T(2. / a0), T(1. / a0)}}, // b0, b1, b2
58 {{
59 T(1.), // a0
60 T(2 * (1 - gamma2) / a0), // a1
61 T((gamma2 + alpha * gamma + 1) / a0), // a2
62 }},
63 };
64 };
65 auto make_fos_norm = [=]() {
66 const double a0 = gamma + 1;
68 {{T(1. / a0), T(1. / a0)}}, // b0, b1
69 {{
70 T(1.), // a0
71 T((1 - gamma) / a0), // a1
72 }},
73 };
74 };
75
76 SOSCoefficients<T, (N + 1) / 2> sections;
77
78 if (N % 2 == 0) {
79 for (uint8_t i = 0; i < sections.length; ++i)
80 sections[i] = normalize ? make_sos_norm(i) : make_sos(i);
81 } else {
82 for (uint8_t i = 0; i < sections.length - 1; ++i)
83 sections[i] = normalize ? make_sos_norm(i) : make_sos(i);
84 sections.end()[-1] = normalize ? make_fos_norm() : make_fos();
85 }
86 return sections;
87}
88
108template <uint8_t N, class T = float, class Implementation = BiQuadFilterDF1<T>>
109SOSFilter<T, (N + 1) / 2, Implementation> butter(double f_n,
110 bool normalize = true) {
111 return butter_coeff<N, T>(f_n, normalize);
112}
113
114
Second Order Sections filter.
Definition: SOSFilter.hpp:22
SOSCoefficients< T,(N+1)/2 > butter_coeff(double f_n, bool normalize=true)
Compute Butterworth filter coefficients.
Definition: Butterworth.hpp:26
SOSFilter< T,(N+1)/2, Implementation > butter(double f_n, bool normalize=true)
Create a Butterworth filter, implemented as Second Order Sections (SOS) filter.
AH::Array< BiQuadCoefficients< T >, N > SOSCoefficients
Definition: SOSFilter.hpp:10
Class for transfer function coefficients.