try to compile with -std=c90 4/n
[liba.git] / include / a / lpf.h
blob8474649f44fcd56fc59a2f0db65bdc9a2e9b4793
1 /*!
2 @file lpf.h
3 @brief Low Pass Filter
4 @details
5 low frequencies are passed, high frequencies are attenuated.
6 \f[
7 RC\frac{\text{d}V_{\mathrm o}}{\text{dt}}+V_{\mathrm o}=V_{\mathrm i}
8 \f]
9 \f[
10 RC\frac{V_{\mathrm o}(n)-V_{\mathrm o}(n-1)}{T_s}+V_{\mathrm o}(n)=V_{\mathrm i}(n)
11 \f]
12 \f[
13 V_{\mathrm o}(n)=\frac{RC}{RC+T_s}V_{\mathrm o}(n-1)+\frac{T_s}{RC+T_s}V_{\mathrm i}(n)
14 \f]
15 \f[
16 V_{\mathrm o}(n)=(1-\alpha)V_{\mathrm o}(n-1)+\alpha V_{\mathrm i}(n)
17 \f]
18 \f[
19 \alpha=\frac{T_s}{RC+T_s}=\frac{T_s}{{\frac{1}{2\pi f_c}}+T_s}
20 \f]
21 https://en.wikipedia.org/wiki/Low-pass_filter
24 #ifndef LIBA_LPF_H
25 #define LIBA_LPF_H
27 #include "math.h"
29 /*!
30 @ingroup liba
31 @addtogroup a_lpf Low Pass Filter
35 /*!
36 @brief instance structure for Low Pass Filter
38 typedef struct a_lpf
40 a_float alpha; /*!< filter coefficient [0,1] */
41 a_float output; /*!< filter output */
42 #if defined(__cplusplus)
43 A_INLINE void gen(a_float fc, a_float ts)
45 alpha = ts / (A_FLOAT_1_TAU / fc + ts);
47 A_INLINE a_float operator()(a_float x)
49 output *= 1 - alpha;
50 output += x * alpha;
51 return output;
53 A_INLINE void zero() { output = 0; }
54 #endif /* __cplusplus */
55 } a_lpf;
56 #if defined(__cplusplus)
57 namespace a
59 typedef struct a_lpf lpf;
60 } /* namespace a */
61 #endif /* __cplusplus */
62 /* clang-format off */
63 #define A_LPF_1(alpha) {a_float_c(alpha), 0}
64 #define A_LPF_2(fc, ts) {A_LPF_GEN(fc, ts), 0}
65 /* clang-format on */
66 #define A_LPF_GEN(fc, ts) (a_float_c(ts) / (A_FLOAT_1_TAU / a_float_c(fc) + a_float_c(ts)))
68 /*!
69 @brief generate for Low Pass Filter
70 \f{cases}{
71 \alpha=\frac{T_s}{RC+T_s},&\alpha\in[0,1]\\
72 RC=\frac{1}{2\pi f_c}.
73 \f}
74 \f[
75 \alpha=\frac{T_s}{\frac{1}{2\pi f_c}+T_s}
76 \f]
77 @param[in] fc cut-off frequency unit(hz)
78 @param[in] ts sampling time unit(s)
79 @return filter coefficient [0,1]
81 A_INTERN a_float a_lpf_gen(a_float fc, a_float ts)
83 return ts / (A_FLOAT_1_TAU / fc + ts);
86 /*!
87 @brief initialize for Low Pass Filter
88 @param[in,out] ctx points to an instance of Low Pass Filter
89 @param[in] alpha filter coefficient [0,1]
91 A_INTERN void a_lpf_init(a_lpf *ctx, a_float alpha)
93 ctx->alpha = alpha;
94 ctx->output = 0;
97 /*!
98 @brief calculate for Low Pass Filter
99 \f[
100 V_{\mathrm o}(n)=(1-\alpha)V_{\mathrm o}(n-1)+\alpha V_{\mathrm i}(n)
102 @param[in,out] ctx points to an instance of Low Pass Filter
103 @param[in] x input value
104 @return output value
106 A_INTERN a_float a_lpf_iter(a_lpf *ctx, a_float x)
108 ctx->output *= 1 - ctx->alpha;
109 ctx->output += x * ctx->alpha;
110 return ctx->output;
114 @brief zeroing for Low Pass Filter
115 @param[in,out] ctx points to an instance of Low Pass Filter
117 A_INTERN void a_lpf_zero(a_lpf *ctx) { ctx->output = 0; }
119 /*! @} a_lpf */
121 #endif /* a/lpf.h */