pub struct EmaFilter {
alpha_q8: u16,
acc: u32,
initialized: bool,
}
impl EmaFilter {
pub const fn new() -> Self {
Self {
alpha_q8: 32,
acc: 0,
initialized: false,
}
}
pub const fn with_alpha(alpha_q8: u16) -> Self {
Self {
alpha_q8,
acc: 0,
initialized: false,
}
}
pub fn update(&mut self, input: u16) -> u16 {
let input_q8 = (input as u32) << 8;
if !self.initialized {
self.acc = input_q8;
self.initialized = true;
} else {
let alpha = self.alpha_q8 as u32;
self.acc = (alpha * input_q8 + (256 - alpha) * self.acc) >> 8;
}
((self.acc + 128) >> 8) as u16
}
pub fn reset(&mut self) {
self.initialized = false;
self.acc = 0;
}
}
impl Default for EmaFilter {
fn default() -> Self {
Self::new()
}
}