Skip to main content

max30102_i2c_nostd/
lib.rs

1//! # max30102-i2c-nostd
2//!
3//! Pilote asynchrone `no_std` pour le capteur MAX30102 (oxymètre de pouls /
4//! capteur de fréquence cardiaque) via I2C, basé sur `embedded-hal-async`.
5//!
6//! Conçu pour fonctionner avec des exécuteurs async embarqués tels
7//! qu'Embassy.
8//!
9//! ## Exemple
10//!
11//! ```ignore
12//! let mut sensor = Max30102::new(i2c, DEFAULT_I2C_ADDR);
13//! sensor.init(&mut delay).await?;
14//!
15//! loop {
16//!     let sample = sensor.read_fifo_sample().await?;
17//!     defmt::info!("red={} ir={}", sample.red, sample.ir);
18//! }
19//! ```
20
21#![no_std]
22#![warn(missing_docs)]
23
24use embedded_hal_async::delay::DelayNs;
25use embedded_hal_async::i2c::I2c;
26
27/// Adresse I2C par défaut du MAX30102.
28pub const DEFAULT_I2C_ADDR: u8 = 0x57;
29
30/// Identifiant de puce attendu (registre `PART_ID`).
31pub const EXPECTED_PART_ID: u8 = 0x15;
32
33/// Registres internes du MAX30102.
34#[allow(dead_code)]
35mod register {
36    pub const INT_STATUS_1: u8 = 0x00;
37    pub const INT_STATUS_2: u8 = 0x01;
38    pub const INT_ENABLE_1: u8 = 0x02;
39    pub const INT_ENABLE_2: u8 = 0x03;
40    pub const FIFO_WR_PTR: u8 = 0x04;
41    pub const FIFO_OVF_COUNTER: u8 = 0x05;
42    pub const FIFO_RD_PTR: u8 = 0x06;
43    pub const FIFO_DATA: u8 = 0x07;
44    pub const FIFO_CONFIG: u8 = 0x08;
45    pub const MODE_CONFIG: u8 = 0x09;
46    pub const SPO2_CONFIG: u8 = 0x0A;
47    pub const LED1_PA: u8 = 0x0C; // LED Rouge
48    pub const LED2_PA: u8 = 0x0D; // LED Infrarouge (IR)
49    pub const MULTI_LED_CTRL1: u8 = 0x11;
50    pub const MULTI_LED_CTRL2: u8 = 0x12;
51    pub const DIE_TEMP_INT: u8 = 0x1F;
52    pub const DIE_TEMP_FRAC: u8 = 0x20;
53    pub const DIE_TEMP_CONFIG: u8 = 0x21;
54    pub const REV_ID: u8 = 0xFE;
55    pub const PART_ID: u8 = 0xFF;
56}
57
58/// Bit de reset logiciel dans `MODE_CONFIG`.
59const MODE_CONFIG_RESET: u8 = 0x40;
60/// Bit de mise en veille (shutdown) dans `MODE_CONFIG`.
61const MODE_CONFIG_SHUTDOWN: u8 = 0x80;
62/// Bit de démarrage de conversion dans `DIE_TEMP_CONFIG`.
63const TEMP_CONFIG_START: u8 = 0x01;
64
65/// Mode de fonctionnement du capteur (registre `MODE_CONFIG`, bits [2:0]).
66#[derive(Debug, Copy, Clone, PartialEq, Eq)]
67pub enum Mode {
68    /// LED Rouge uniquement (fréquence cardiaque).
69    HeartRateOnly = 0x02,
70    /// LED Rouge + Infrarouge (SpO2).
71    Spo2 = 0x03,
72    /// LED Rouge + Infrarouge + Verte, contrôle multi-LED (multi-LED mode).
73    MultiLed = 0x07,
74}
75
76/// Nombre d'échantillons moyennés dans le FIFO (registre `FIFO_CONFIG`, bits [6:5]).
77#[derive(Debug, Copy, Clone, PartialEq, Eq)]
78pub enum SampleAveraging {
79    /// Pas de moyennage.
80    Sa1 = 0b000,
81    /// Moyenne sur 2 échantillons.
82    Sa2 = 0b001,
83    /// Moyenne sur 4 échantillons.
84    Sa4 = 0b010,
85    /// Moyenne sur 8 échantillons.
86    Sa8 = 0b011,
87    /// Moyenne sur 16 échantillons.
88    Sa16 = 0b100,
89    /// Moyenne sur 32 échantillons.
90    Sa32 = 0b101,
91}
92
93/// Configuration matérielle appliquée lors de [`Max30102::init`].
94#[derive(Debug, Copy, Clone, PartialEq, Eq)]
95pub struct Config {
96    /// Mode de fonctionnement (Rouge seul / SpO2 / multi-LED).
97    pub mode: Mode,
98    /// Valeur brute du registre `SPO2_CONFIG` (plage ADC, fréquence
99    /// d'échantillonnage, largeur d'impulsion LED). Valeur par défaut :
100    /// ADC 4096nA, 100 Hz, impulsion 411 µs.
101    pub spo2_config: u8,
102    /// Courant de la LED Rouge (0x00–0xFF, ~0.2 mA par pas).
103    pub led_red_current: u8,
104    /// Courant de la LED Infrarouge (0x00–0xFF, ~0.2 mA par pas).
105    pub led_ir_current: u8,
106    /// Moyennage des échantillons dans le FIFO.
107    pub sample_averaging: SampleAveraging,
108    /// Active le retard de lecture (`FIFO_A_FULL`) via le FIFO rolling-over.
109    pub fifo_rollover_en: bool,
110}
111
112impl Default for Config {
113    fn default() -> Self {
114        Self {
115            mode: Mode::Spo2,
116            spo2_config: 0x27, // ADC 4096nA, 100 Hz, 411 µs
117            led_red_current: 0x24,
118            led_ir_current: 0x24,
119            sample_averaging: SampleAveraging::Sa4,
120            fifo_rollover_en: true,
121        }
122    }
123}
124
125/// Un échantillon brut lu depuis le FIFO (18 bits utiles par canal).
126#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
127pub struct Sample {
128    /// Valeur brute du canal Rouge.
129    pub red: u32,
130    /// Valeur brute du canal Infrarouge.
131    pub ir: u32,
132}
133
134/// Erreurs possibles du pilote MAX30102.
135#[derive(Debug, Copy, Clone, PartialEq, Eq)]
136pub enum Error<E> {
137    /// Erreur liée au bus I2C sous-jacent.
138    I2c(E),
139    /// Identifiant de puce invalide (mauvais capteur ou mauvaise adresse).
140    InvalidPartId {
141        /// Identifiant réellement lu sur le bus.
142        found: u8,
143    },
144}
145
146impl<E> From<E> for Error<E> {
147    fn from(error: E) -> Self {
148        Error::I2c(error)
149    }
150}
151
152/// Pilote principal du capteur MAX30102.
153pub struct Max30102<I2C> {
154    i2c: I2C,
155    address: u8,
156}
157
158impl<I2C, E> Max30102<I2C>
159where
160    I2C: I2c<Error = E>,
161{
162    /// Crée une nouvelle instance du capteur à partir d'un bus I2C et d'une
163    /// adresse (utiliser [`DEFAULT_I2C_ADDR`] dans le cas courant).
164    pub fn new(i2c: I2C, address: u8) -> Self {
165        Self { i2c, address }
166    }
167
168    /// Libère le bus I2C sous-jacent, consommant le pilote.
169    pub fn release(self) -> I2C {
170        self.i2c
171    }
172
173    /// Initialisation complète avec la configuration par défaut
174    /// (voir [`Config::default`]).
175    pub async fn init<D: DelayNs>(&mut self, delay: &mut D) -> Result<(), Error<E>> {
176        self.init_with_config(delay, Config::default()).await
177    }
178
179    /// Initialisation complète avec une configuration personnalisée.
180    pub async fn init_with_config<D: DelayNs>(
181        &mut self,
182        delay: &mut D,
183        config: Config,
184    ) -> Result<(), Error<E>> {
185        // 1. Réinitialisation matérielle (soft reset) et attente de la fin
186        //    du reset (le bit MODE_CONFIG_RESET retombe automatiquement à 0).
187        self.write_register(register::MODE_CONFIG, MODE_CONFIG_RESET)
188            .await?;
189        delay.delay_ms(100).await;
190
191        // 2. Vérification de l'identifiant de la puce.
192        self.verify_part_id().await?;
193
194        // 3. Configuration du FIFO (moyennage + rollover) et purge.
195        let fifo_cfg = ((config.sample_averaging as u8) << 5)
196            | if config.fifo_rollover_en { 0x10 } else { 0x00 };
197        self.write_register(register::FIFO_CONFIG, fifo_cfg).await?;
198        self.clear_fifo().await?;
199
200        // 4. Configuration du mode de fonctionnement.
201        self.write_register(register::MODE_CONFIG, config.mode as u8)
202            .await?;
203
204        // 5. Configuration SpO2 (plage ADC, fréquence, largeur d'impulsion).
205        self.write_register(register::SPO2_CONFIG, config.spo2_config)
206            .await?;
207
208        // 6. Réglage du courant des LED.
209        self.write_register(register::LED1_PA, config.led_red_current)
210            .await?;
211        self.write_register(register::LED2_PA, config.led_ir_current)
212            .await?;
213
214        Ok(())
215    }
216
217    /// Vérifie que l'identifiant de la puce correspond à [`EXPECTED_PART_ID`].
218    ///
219    /// Retourne une erreur [`Error::InvalidPartId`] si l'identifiant ne
220    /// correspond pas.
221    pub async fn verify_part_id(&mut self) -> Result<(), Error<E>> {
222        let id = self.read_register(register::PART_ID).await?;
223        if id != EXPECTED_PART_ID {
224            return Err(Error::InvalidPartId { found: id });
225        }
226        Ok(())
227    }
228
229    /// Réinitialise les pointeurs du FIFO (lecture, écriture, débordement).
230    pub async fn clear_fifo(&mut self) -> Result<(), Error<E>> {
231        self.write_register(register::FIFO_WR_PTR, 0x00).await?;
232        self.write_register(register::FIFO_OVF_COUNTER, 0x00).await?;
233        self.write_register(register::FIFO_RD_PTR, 0x00).await?;
234        Ok(())
235    }
236
237    /// Nombre d'échantillons disponibles dans le FIFO (calculé à partir des
238    /// pointeurs de lecture/écriture matériels).
239    pub async fn available_samples(&mut self) -> Result<u8, Error<E>> {
240        let wr = self.read_register(register::FIFO_WR_PTR).await?;
241        let rd = self.read_register(register::FIFO_RD_PTR).await?;
242        Ok(wr.wrapping_sub(rd) & 0x1F)
243    }
244
245    /// Lit un échantillon complet du FIFO (canaux Rouge et Infrarouge).
246    ///
247    /// À appeler uniquement lorsque [`Max30102::available_samples`] indique
248    /// qu'au moins un échantillon est disponible, ou après une interruption
249    /// `FIFO_A_FULL` / `PPG_RDY`.
250    pub async fn read_fifo_sample(&mut self) -> Result<Sample, Error<E>> {
251        let mut data = [0u8; 6];
252        self.i2c
253            .write_read(self.address, &[register::FIFO_DATA], &mut data)
254            .await?;
255
256        // Le MAX30102 stocke les données sur 18 bits par canal (3 octets),
257        // alignées à droite dans chaque triplet.
258        let red = (((data[0] as u32) << 16) | ((data[1] as u32) << 8) | (data[2] as u32))
259            & 0x03FFFF;
260        let ir = (((data[3] as u32) << 16) | ((data[4] as u32) << 8) | (data[5] as u32))
261            & 0x03FFFF;
262
263        Ok(Sample { red, ir })
264    }
265
266    /// Modifie le courant de la LED Rouge sans réinitialiser le capteur.
267    pub async fn set_red_led_current(&mut self, value: u8) -> Result<(), Error<E>> {
268        self.write_register(register::LED1_PA, value).await
269    }
270
271    /// Modifie le courant de la LED Infrarouge sans réinitialiser le capteur.
272    pub async fn set_ir_led_current(&mut self, value: u8) -> Result<(), Error<E>> {
273        self.write_register(register::LED2_PA, value).await
274    }
275
276    /// Déclenche une mesure de température interne (température du die) et
277    /// la retourne en degrés Celsius. La conversion prend environ 29 ms.
278    pub async fn read_temperature<D: DelayNs>(
279        &mut self,
280        delay: &mut D,
281    ) -> Result<f32, Error<E>> {
282        self.write_register(register::DIE_TEMP_CONFIG, TEMP_CONFIG_START)
283            .await?;
284        delay.delay_ms(30).await;
285
286        let int_part = self.read_register(register::DIE_TEMP_INT).await? as i8;
287        let frac_part = self.read_register(register::DIE_TEMP_FRAC).await?;
288
289        Ok(int_part as f32 + (frac_part as f32) * 0.0625)
290    }
291
292    /// Place le capteur en veille (faible consommation). Le contenu des
293    /// registres de configuration est conservé.
294    pub async fn shutdown(&mut self) -> Result<(), Error<E>> {
295        let current = self.read_register(register::MODE_CONFIG).await?;
296        self.write_register(register::MODE_CONFIG, current | MODE_CONFIG_SHUTDOWN)
297            .await
298    }
299
300    /// Réveille le capteur après un [`Max30102::shutdown`].
301    pub async fn wake_up(&mut self) -> Result<(), Error<E>> {
302        let current = self.read_register(register::MODE_CONFIG).await?;
303        self.write_register(register::MODE_CONFIG, current & !MODE_CONFIG_SHUTDOWN)
304            .await
305    }
306
307    /// Lit l'identifiant de révision matérielle (registre `REV_ID`).
308    pub async fn revision_id(&mut self) -> Result<u8, Error<E>> {
309        self.read_register(register::REV_ID).await
310    }
311
312    /// Lecture brute d'un registre 8 bits.
313    async fn read_register(&mut self, reg: u8) -> Result<u8, Error<E>> {
314        let mut data = [0u8; 1];
315        self.i2c
316            .write_read(self.address, &[reg], &mut data)
317            .await?;
318        Ok(data[0])
319    }
320
321    /// Écriture brute d'un registre 8 bits.
322    async fn write_register(&mut self, reg: u8, val: u8) -> Result<(), Error<E>> {
323        self.i2c.write(self.address, &[reg, val]).await?;
324        Ok(())
325    }
326}