use alloc::vec::Vec;
use core::f32::consts::PI;
#[derive(Clone, Debug)]
pub struct Smooth {
n: usize,
readings: Vec<f32>,
read_index: usize,
average: f32,
}
impl Smooth {
pub fn new(num_readings: usize) -> Self {
Smooth {
n: num_readings,
readings: vec![0.0; num_readings],
read_index: 0,
average: 0.0,
}
}
pub fn add_reading(&mut self, reading: f32) {
self.readings[self.read_index] = reading;
self.read_index += 1;
self.read_index %= self.n;
self.average = self.readings.iter().fold(0.0, |s, &x| s + x) / self.n as f32;
}
pub fn get_average(&self) -> f32 {
self.average
}
}
#[derive(Copy, Clone, Debug)]
pub struct HPFilter {
output: f32,
tau: f32,
}
impl HPFilter {
pub fn new(fc: f32) -> Self {
HPFilter {
output: 0.0,
tau : 1. / (2.0 * PI * fc),
}
}
pub fn compute(&mut self, input: f32, old_input: f32, old_output: f32, dt: f32) -> f32 {
self.output = old_output + (input - old_input) - (dt / self.tau) * old_output;
self.output
}
pub fn get_output(&self) -> f32 {
self.output
}
}
#[derive(Copy, Clone, Debug)]
pub struct LPFilter {
output: f32,
tau: f32,
}
impl LPFilter {
pub fn new(fc: f32) -> Self {
LPFilter {
output: 0.0,
tau : 1. / (2.0 * PI * fc),
}
}
pub fn compute(&mut self, input: f32, old_output: f32, dt: f32) -> f32 {
self.output = old_output + (input - old_output) * (dt / self.tau);
self.output
}
pub fn get_output(&self) -> f32 {
self.output
}
}