From 2e9c1d14677be6efaf66f4b962b5e2a908dccec5 Mon Sep 17 00:00:00 2001 From: atse Date: Fri, 26 Jan 2024 13:04:20 +0800 Subject: [PATCH] Average out reads instead of waiting for stability Reading until the error falls into a certain tolerance might cause bootlooping as the ADC values just might never settle. Average it out instead. --- src/channels.rs | 33 ++++++++++++++++----------------- 1 file changed, 16 insertions(+), 17 deletions(-) diff --git a/src/channels.rs b/src/channels.rs index e33a0b6..c62cab2 100644 --- a/src/channels.rs +++ b/src/channels.rs @@ -169,17 +169,6 @@ impl<'a> Channels<'a> { } } - pub fn read_dac_feedback_until_stable(&mut self, channel: usize, tolerance: ElectricPotential) -> ElectricPotential { - let mut prev = self.read_dac_feedback(channel); - loop { - let current = self.read_dac_feedback(channel); - if (current - prev).abs() < tolerance { - return current; - } - prev = current; - } - } - pub fn read_itec(&mut self, channel: usize) -> ElectricPotential { match channel { 0 => { @@ -265,11 +254,14 @@ impl<'a> Channels<'a> { /// thermostat. pub fn calibrate_dac_value(&mut self, channel: usize) { let samples = 50; - let mut target_voltage = ElectricPotential::new::(0.0); - for _ in 0..samples { - target_voltage += self.read_vref(channel); - } - target_voltage /= samples as f64; + let target_voltage = { + let mut target_voltage = ElectricPotential::new::(0.0); + for _ in 0..samples { + target_voltage += self.read_vref(channel); + } + target_voltage /= samples as f64; + target_voltage + }; let mut start_value = 1; let mut best_error = ElectricPotential::new::(100.0); @@ -287,7 +279,14 @@ impl<'a> Channels<'a> { _ => unreachable!(), } - let dac_feedback = self.read_dac_feedback_until_stable(channel, ElectricPotential::new::(0.001)); + let dac_feedback = { + let mut dac_feedback = ElectricPotential::new::(0.0); + for _ in 0..samples { + dac_feedback += self.read_dac_feedback(channel); + } + dac_feedback /= samples as f64; + dac_feedback + }; let error = target_voltage - dac_feedback; if error < ElectricPotential::new::(0.0) { break;