humidity_core/sample/
mod.rs

1//! # Sampling results
2//!
3//! Establish a common ground to work with the results of a sampling operation.
4//! Uses [`Summary`] to hold the results of a sampling operation.
5
6pub use summary::Summary;
7
8use crate::sensors;
9
10mod summary;
11
12pub fn perform_sampling<SENSOR: sensors::Sensor>(
13    n: u8,
14    toggle_sensor: &mut impl FnMut(),
15    warmup_delay: &mut impl FnMut(),
16    adc_read: &mut impl FnMut() -> u16,
17    sensor: SENSOR,
18) -> Summary<SENSOR> {
19    let mut sum = 0u32;
20    let mut min = u16::MAX;
21    let mut max = u16::MIN;
22
23    toggle_sensor();
24    warmup_delay();
25
26    // Trigger 3 warm-up reads.
27    adc_read();
28    adc_read();
29    adc_read();
30
31    // Proceed with sampling.
32    for _ in 0..n {
33        let sample = adc_read();
34        max = max.max(sample);
35        min = min.min(sample);
36        sum += sample as u32;
37    }
38    toggle_sensor();
39
40    let avg = sum.div_ceil(n as u32) as u16;
41    Summary::<SENSOR> { n, avg, min, max, sensor }
42}