Skip to main content

m5stack_core/io/
rpm.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2use embassy_time::{Duration, Ticker};
3use esp_hal::gpio::{AnyPin, Input, InputConfig};
4
5use crate::driver::pcnt::PcntDriver;
6
7/// Sampling window for the pulse counter.
8///
9/// Deliberately the ONLY knob here. Pole pairs and pulley geometry describe the
10/// alternator and the engine it is bolted to, not the board — a BSP that knows
11/// them cannot be reused on a different vehicle. The application converts the
12/// pulse rate below into engine rpm.
13pub struct RpmConfig {
14    pub loop_time_ms: u64,
15}
16
17pub struct RpmResources<'a> {
18    pub pcnt: esp_hal::peripherals::PCNT0_UNIT1<'a>,
19    pub pin: AnyPin<'a>,
20}
21
22impl RpmResources<'static> {
23    pub fn into_driver(self) -> PcntDriver {
24        let input = Input::new(
25            self.pin,
26            InputConfig::default().with_pull(esp_hal::gpio::Pull::Down),
27        );
28        PcntDriver::new(self.pcnt, input)
29    }
30}
31
32/// Single-shot read of the sensor's pulse rate, in Hz.
33///
34/// What the hardware actually measures. Turning Hz into engine rpm needs the
35/// alternator's pole count and the pulley ratio, which are the application's
36/// to know.
37pub fn read_pulse_hz(pcnt: &mut PcntDriver, config: &RpmConfig) -> f32 {
38    let pulse_count = pcnt.get_and_reset();
39    pulse_count as f32 * (1000. / config.loop_time_ms as f32) // intervals per second
40}
41
42/// Number of consecutive zero-pulse intervals before we report "no signal"
43/// (NaN) instead of "engine stopped" (0.0). At the default 100 ms interval
44/// this is 3 s.
45const NO_SIGNAL_INTERVALS: u32 = 30;
46
47/// Convenience loop: ticker + [`read_pulse_hz`] + callback.
48///
49/// `on_pulse_hz` is invoked only on **state transitions**, so callers that
50/// store into a shared atomic don't get hammered every 100 ms:
51///   * each non-zero reading       → pulse rate in Hz
52///   * first zero after non-zero   → `0.0` (engine just stopped)
53///   * [`NO_SIGNAL_INTERVALS`] zeros → `f32::NAN` (signal lost)
54///
55/// Both sentinels survive any linear Hz→rpm conversion the caller applies
56/// (`0.0 * k == 0.0`, `NAN * k == NAN`), so the application does not have to
57/// special-case them.
58///
59/// Between the "stopped" and "no signal" transitions the callback is
60/// silent, which lets HIL-injected values stick once the rig has been
61/// idle long enough.
62pub async fn pulse_loop(resources: RpmResources<'static>, config: RpmConfig, on_pulse_hz: fn(f32)) {
63    let mut pcnt_driver = resources.into_driver();
64    let mut ticker = Ticker::every(Duration::from_millis(config.loop_time_ms));
65    let mut zero_intervals: u32 = 0;
66    loop {
67        let hz = read_pulse_hz(&mut pcnt_driver, &config);
68        if hz > 0.0 {
69            zero_intervals = 0;
70            on_pulse_hz(hz);
71        } else {
72            let prev = zero_intervals;
73            zero_intervals = zero_intervals.saturating_add(1);
74            if prev == 0 {
75                on_pulse_hz(0.0); // transition: running → stopped
76            } else if prev == NO_SIGNAL_INTERVALS {
77                on_pulse_hz(f32::NAN); // transition: stopped → no signal
78            }
79            // else: PROCESS_DATA untouched
80        }
81        ticker.next().await;
82    }
83}