Skip to main content

m5stack_core/driver/
pps.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! M5Stack PPS module (SKU U136) driver, I2C address 0x35.
3//!
4//! The module serves one RAM register bank; reads auto-increment through it and
5//! writes land in it. The full map, who writes what, and the bus timing it was
6//! measured with are in `docs/pps-register-map.md`. This driver touches only
7//! `0x00..=0x1F`:
8//!
9//! | Addr | Bytes | Register | Writer |
10//! |---|---|---|---|
11//! | 0x00 | 2 | module ID, always `0x1041` | module |
12//! | 0x04 | 1 | ENABLE, 0 = output off | host |
13//! | 0x05 | 1 | running mode 0 off / 1 CV / 2 CC | module, after it switched the output |
14//! | 0x07 | 1 | FLAG, +1 per measurement refresh (~16 Hz), wraps | module |
15//! | 0x08..=0x17 | 4 × f32 | output V, output A, °C, input V | module |
16//! | 0x18..=0x1F | 2 × f32 | voltage set, current set | host |
17//!
18//! The module applies the setpoints whether or not the output is enabled, and
19//! does NOT reject out-of-range ones: the caller clamps.
20//!
21//! Two bus properties shape every caller (measured, 2026-10-17): the module
22//! holds SCL for 100-200 us while it copies the bank for a read, and it NACKs a
23//! transaction addressed right after another one ended. See [`crate::io::pps`].
24use thiserror_no_std::Error;
25
26use crate::io::shared_i2c::SharedI2cBus;
27
28#[repr(u8)]
29#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
30pub enum PpsRunningMode {
31    Off = 0,
32    Voltage = 1,
33    Current = 2,
34    #[default]
35    Unknown = 3,
36}
37
38impl PpsRunningMode {
39    pub fn from_u8(v: u8) -> Option<Self> {
40        match v {
41            0 => Some(Self::Off),
42            1 => Some(Self::Voltage),
43            2 => Some(Self::Current),
44            3 => Some(Self::Unknown),
45            _ => None,
46        }
47    }
48}
49
50#[derive(Debug, Error)]
51pub enum PpsError {
52    /// Module answered correctly but had no measurement (NaN readback).
53    /// Not a bus failure: it is healthy and will answer next cycle.
54    #[error("PPS reported no valid measurement")]
55    NotReady,
56
57    /// A finite reading outside any range the hardware can produce.
58    #[error("PPS reading {0} outside the plausible range for {1}")]
59    OutOfRange(f32, &'static str),
60
61    /// A running-mode byte the module firmware never writes.
62    #[error("PPS running mode {0} is not a known mode")]
63    BadMode(u8),
64
65    /// Something answered at the PPS address, but it is not a PPS module.
66    #[error("device reports module id {0:#06x}, not a PPS module")]
67    WrongDevice(u16),
68
69    #[error("I2C master error: {0:?}")]
70    I2cMasterError(#[from] esp_hal::i2c::master::Error),
71}
72
73impl PpsError {
74    /// The module answered, just not with a usable reading: the link is fine.
75    pub fn is_transient(&self) -> bool {
76        matches!(
77            self,
78            PpsError::NotReady | PpsError::OutOfRange(..) | PpsError::BadMode(_)
79        )
80    }
81}
82
83/// Module ID at registers 0x00/0x01, hardcoded by the module's own firmware
84/// (<https://github.com/m5stack/M5Module-PPS-Internal-FW> `Core/Src/i2c_comm.c`).
85pub const MODULE_ID: u16 = 0x1041;
86
87/// The module's I2C address as shipped.
88pub const ADDRESS: u8 = 0x35;
89
90/// Plausibility bounds: reject only what the hardware cannot produce, never
91/// application limits. A tighter bound would eventually drop a real reading.
92/// Second net only, since a wrong-but-plausible value passes.
93const VOLTAGE_RANGE: (f32, f32) = (-1.0, 60.0); // V, module output + input rails
94const CURRENT_RANGE: (f32, f32) = (-1.0, 20.0); // A, module output
95const TEMPERATURE_RANGE: (f32, f32) = (-40.0, 150.0); // degC, sensor span
96
97/// Accept a reading only if finite and physically possible. Without this the
98/// module's own "no measurement" answer (NaN) is published as fact.
99fn checked(value: f32, range: (f32, f32), what: &'static str) -> Result<f32, PpsError> {
100    if !value.is_finite() {
101        return Err(PpsError::NotReady);
102    }
103    if value < range.0 || value > range.1 {
104        return Err(PpsError::OutOfRange(value, what));
105    }
106    Ok(value)
107}
108
109const REG_MODULE_ID: u8 = 0x00;
110const REG_ENABLE: u8 = 0x04;
111const REG_VOUT_SET: u8 = 0x18;
112/// First and length of the bank [`PpsDriver::read_bank`] reads: ENABLE..=IOUT set.
113const BANK_FIRST: u8 = REG_ENABLE;
114const BANK_LEN: usize = 0x20 - BANK_FIRST as usize;
115
116/// One read of `0x04..=0x1F`: the module's state and what it was last told.
117#[derive(Debug, Clone, Copy)]
118pub struct PpsBank {
119    /// ENABLE as the module holds it, i.e. the last value written.
120    pub enabled: bool,
121    pub running_mode: PpsRunningMode,
122    /// Measurement sequence number; advances on every refresh.
123    pub flag: u8,
124    pub voltage: f32,
125    pub current: f32,
126    pub temperature: f32,
127    pub input_voltage: f32,
128    /// The setpoints as the module holds them, i.e. the last values written.
129    pub voltage_set: f32,
130    pub current_set: f32,
131}
132
133impl PpsBank {
134    /// Decode the bytes read from [`BANK_FIRST`].
135    fn decode(b: &[u8; BANK_LEN]) -> Result<Self, PpsError> {
136        let at = |reg: usize| reg - BANK_FIRST as usize;
137        let f = |reg: usize| {
138            let i = at(reg);
139            f32::from_le_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]])
140        };
141        let mode = b[at(0x05)];
142        Ok(Self {
143            enabled: b[at(0x04)] != 0,
144            running_mode: PpsRunningMode::from_u8(mode).ok_or(PpsError::BadMode(mode))?,
145            flag: b[at(0x07)],
146            voltage: checked(f(0x08), VOLTAGE_RANGE, "readback voltage")?,
147            current: checked(f(0x0C), CURRENT_RANGE, "readback current")?,
148            temperature: checked(f(0x10), TEMPERATURE_RANGE, "temperature")?,
149            input_voltage: checked(f(0x14), VOLTAGE_RANGE, "input voltage")?,
150            voltage_set: f(0x18),
151            current_set: f(0x1C),
152        })
153    }
154}
155
156pub struct PpsDriver {
157    i2c: &'static SharedI2cBus,
158    address: u8,
159}
160
161impl PpsDriver {
162    pub fn new(i2c: &'static SharedI2cBus, address: u8) -> Self {
163        Self { i2c, address }
164    }
165
166    async fn read(&self, first: u8, buf: &mut [u8]) -> Result<(), PpsError> {
167        let mut bus = self.i2c.lock().await;
168        bus.write_read_async(self.address, &[first], buf).await?;
169        Ok(())
170    }
171
172    async fn write(&self, bytes: &[u8]) -> Result<(), PpsError> {
173        let mut bus = self.i2c.lock().await;
174        bus.write_async(self.address, bytes).await?;
175        Ok(())
176    }
177
178    /// Confirm the right device is answering. [`MODULE_ID`] does not depend on
179    /// a conversion, so it validates address, framing and byte order.
180    pub async fn probe(&mut self) -> Result<u16, PpsError> {
181        let mut b = [0_u8; 2];
182        self.read(REG_MODULE_ID, &mut b).await?;
183        let id = u16::from_le_bytes(b);
184        if id != MODULE_ID {
185            return Err(PpsError::WrongDevice(id));
186        }
187        Ok(id)
188    }
189
190    /// `0x04..=0x1F` in one transaction: state, measurements and setpoints.
191    pub async fn read_bank(&mut self) -> Result<PpsBank, PpsError> {
192        let mut b = [0_u8; BANK_LEN];
193        self.read(BANK_FIRST, &mut b).await?;
194        PpsBank::decode(&b)
195    }
196
197    /// Voltage and current setpoints in one 8-byte write. Not range-checked
198    /// here, and the module does not check either: the caller clamps.
199    pub async fn write_setpoints(&mut self, voltage: f32, current: f32) -> Result<(), PpsError> {
200        let mut b = [0_u8; 9];
201        b[0] = REG_VOUT_SET;
202        b[1..5].copy_from_slice(&voltage.to_le_bytes());
203        b[5..9].copy_from_slice(&current.to_le_bytes());
204        self.write(&b).await
205    }
206
207    pub async fn write_enable(&mut self, enabled: bool) -> Result<(), PpsError> {
208        self.write(&[REG_ENABLE, enabled as u8]).await
209    }
210}