Skip to main content

lsm303_driver/
lib.rs

1// part how this code is a translation from https://github.com/pololu/lsm303-arduino
2//! A `no_std` driver for the ST LSM303 accelerometer + magnetometer family
3//! (also sold as the **GY-511** breakout board):
4//!
5//! - LSM303DLH
6//! - LSM303DLM
7//! - LSM303DLHC
8//! - LSM303D
9//!
10//! Built on `embedded-hal` 1.0. It is async by default; enable the `sync`
11//! feature for the blocking API.
12//!
13//! # Usage
14//!
15//! ```ignore
16//! use lsm303_driver::{Lsm303, D, SA0};
17//!
18//! // `i2c` is any `embedded_hal_async::i2c::I2c` implementation.
19//! let mut sensor = Lsm303::<_, D>::new(i2c, SA0::High);
20//! sensor.enable_default().await?;
21//!
22//! let (accel, mag) = sensor.read().await?;
23//! // accel.x, accel.y, accel.z, mag.x, mag.y, mag.z (raw i16 counts)
24//! ```
25//!
26//! Don't know which chip you have? Let the driver detect it:
27//!
28//! ```ignore
29//! use lsm303_driver::{AnyLsm303, Lsm303, D};
30//!
31//! let found = AnyLsm303::detect(&mut i2c, None, None).await?;
32//!
33//! let mut sensor: Lsm303<_, D> = match found.into_driver(i2c) {
34//!     Ok(sensor) => sensor,
35//!     Err(other) => panic!("expected an LSM303D, found {:?}", other),
36//! };
37//! sensor.enable_default().await?;
38//! ```
39//!
40//! # Status
41//!
42//! Tested only on the **LSM303D**. The other variants are implemented from
43//! their datasheets but not yet tested on hardware.
44
45#![no_std]
46
47// `sync` and `async` select which `embedded-hal` I2c trait the driver is built
48// against, so exactly one must be active. Cargo features are additive, so guard
49// against a dependency turning on the other one behind your back.
50#[cfg(all(feature = "sync", feature = "async"))]
51compile_error!(
52    "features `sync` and `async` are mutually exclusive - enable exactly one \
53     (e.g. `default-features = false, features = [\"sync\"]`)"
54);
55
56#[cfg(not(any(feature = "sync", feature = "async")))]
57compile_error!("enable exactly one of the `sync` or `async` features");
58
59mod lsm303_registers;
60#[cfg(test)]
61mod tests;
62
63use lsm303_registers::*;
64
65use crate::lsm303_registers::reg_addr::{TEMP_OUT_H, TEMP_OUT_L};
66use core::marker::PhantomData;
67#[cfg(feature = "sync")]
68use embedded_hal::i2c::{Error as _, ErrorKind, I2c};
69#[cfg(feature = "async")]
70use embedded_hal_async::i2c::{Error as _, ErrorKind, I2c};
71
72// Full-scale range enums.
73//
74// Each `bits()` returns the register field value already shifted into position,
75// and `MASK` is that field's bit mask, so a setter does a read-modify-write of
76// exactly those bits.
77//
78// The bit encodings below are verified against the ST datasheets (LSM303DLH,
79// LSM303DLHC, LSM303D). Note DLH/DLM encode 8 g as `FS = 0b11` while the DLHC
80// uses `0b10`, which is why the accelerometer scales are separate enums.
81
82/// Magnetometer full-scale range for the DLH/DLM/DLHC (`GN[2:0]` in `CRB_REG_M`).
83#[derive(Clone, Copy, PartialEq, Eq, Debug)]
84#[cfg_attr(feature = "defmt", derive(defmt::Format))]
85pub enum DlxMagScale {
86    G1_3,
87    G1_9,
88    G2_5,
89    G4_0,
90    G4_7,
91    G5_6,
92    G8_1,
93}
94
95impl DlxMagScale {
96    /// `GN[2:0]` field mask in `CRB_REG_M` (bits 7:5).
97    const MASK: u8 = 0b1110_0000;
98
99    fn bits(self) -> u8 {
100        match self {
101            DlxMagScale::G1_3 => 0b001 << 5,
102            DlxMagScale::G1_9 => 0b010 << 5,
103            DlxMagScale::G2_5 => 0b011 << 5,
104            DlxMagScale::G4_0 => 0b100 << 5,
105            DlxMagScale::G4_7 => 0b101 << 5,
106            DlxMagScale::G5_6 => 0b110 << 5,
107            DlxMagScale::G8_1 => 0b111 << 5,
108        }
109    }
110}
111
112/// Magnetometer full-scale range for the LSM303D (`MFS[1:0]` in `CTRL6`).
113#[derive(Clone, Copy, PartialEq, Eq, Debug)]
114#[cfg_attr(feature = "defmt", derive(defmt::Format))]
115pub enum DMagScale {
116    G2,
117    G4,
118    G8,
119    G12,
120}
121
122impl DMagScale {
123    /// `MFS[1:0]` field mask in `CTRL6` (bits 6:5).
124    const MASK: u8 = 0b0110_0000;
125
126    fn bits(self) -> u8 {
127        match self {
128            DMagScale::G2 => 0b00 << 5,
129            DMagScale::G4 => 0b01 << 5,
130            DMagScale::G8 => 0b10 << 5,
131            DMagScale::G12 => 0b11 << 5,
132        }
133    }
134}
135
136/// Accelerometer full-scale range for the DLH and DLM (`FS[1:0]` in `CTRL_REG4_A`).
137#[derive(Clone, Copy, PartialEq, Eq, Debug)]
138#[cfg_attr(feature = "defmt", derive(defmt::Format))]
139pub enum DlhDlmAccScale {
140    G2,
141    G4,
142    G8,
143}
144
145impl DlhDlmAccScale {
146    /// `FS[1:0]` field mask in `CTRL_REG4_A` (bits 5:4).
147    const MASK: u8 = 0b0011_0000;
148
149    fn bits(self) -> u8 {
150        // NB: DLH/DLM encode 8 g as FS = 0b11 (0b10 is unused).
151        match self {
152            DlhDlmAccScale::G2 => 0b00 << 4,
153            DlhDlmAccScale::G4 => 0b01 << 4,
154            DlhDlmAccScale::G8 => 0b11 << 4,
155        }
156    }
157
158    /// Decode the current range from a raw `CTRL_REG4_A` value.
159    fn from_reg(reg: u8) -> Self {
160        match reg & Self::MASK {
161            0x10 => DlhDlmAccScale::G4,
162            0x30 => DlhDlmAccScale::G8,
163            _ => DlhDlmAccScale::G2,
164        }
165    }
166}
167
168/// Accelerometer full-scale range for the DLHC (`FS[1:0]` in `CTRL_REG4_A`).
169#[derive(Clone, Copy, PartialEq, Eq, Debug)]
170#[cfg_attr(feature = "defmt", derive(defmt::Format))]
171pub enum DlhcAccScale {
172    G2,
173    G4,
174    G8,
175    G16,
176}
177
178impl DlhcAccScale {
179    /// `FS[1:0]` field mask in `CTRL_REG4_A` (bits 5:4).
180    const MASK: u8 = 0b0011_0000;
181
182    fn bits(self) -> u8 {
183        // NB: the DLHC encodes 8 g as FS = 0b10 (unlike DLH/DLM's 0b11).
184        match self {
185            DlhcAccScale::G2 => 0b00 << 4,
186            DlhcAccScale::G4 => 0b01 << 4,
187            DlhcAccScale::G8 => 0b10 << 4,
188            DlhcAccScale::G16 => 0b11 << 4,
189        }
190    }
191
192    /// Decode the current range from a raw `CTRL_REG4_A` value.
193    fn from_reg(reg: u8) -> Self {
194        match reg & Self::MASK {
195            0x10 => DlhcAccScale::G4,
196            0x20 => DlhcAccScale::G8,
197            0x30 => DlhcAccScale::G16,
198            _ => DlhcAccScale::G2,
199        }
200    }
201}
202
203/// Accelerometer full-scale range for the LSM303D (`AFS[2:0]` in `CTRL2`).
204#[derive(Clone, Copy, PartialEq, Eq, Debug)]
205#[cfg_attr(feature = "defmt", derive(defmt::Format))]
206pub enum DAccScale {
207    G2,
208    G4,
209    G6,
210    G8,
211    G16,
212}
213
214impl DAccScale {
215    /// `AFS[2:0]` field mask in `CTRL2` (bits 5:3).
216    const MASK: u8 = 0b0011_1000;
217
218    fn bits(self) -> u8 {
219        match self {
220            DAccScale::G2 => 0b000 << 3,
221            DAccScale::G4 => 0b001 << 3,
222            DAccScale::G6 => 0b010 << 3,
223            DAccScale::G8 => 0b011 << 3,
224            DAccScale::G16 => 0b100 << 3,
225        }
226    }
227
228    /// Decode the current range from a raw `CTRL2` value.
229    fn from_reg(reg: u8) -> Self {
230        match reg & Self::MASK {
231            0x08 => DAccScale::G4,
232            0x10 => DAccScale::G6,
233            0x18 => DAccScale::G8,
234            0x20 => DAccScale::G16,
235            _ => DAccScale::G2,
236        }
237    }
238}
239
240// Output-data-rate enums (verified against the ST datasheets).
241
242/// Accelerometer output data rate for the DLH and DLM (`CTRL_REG1_A`).
243///
244/// These chips select the rate via the `DR` field but only produce data in
245/// normal power mode, so setting a rate also forces `PM = normal`; `PowerDown`
246/// sets `PM = power-down`. Encoded across `PM[2:0]` (bits 7:5) and `DR[1:0]`
247/// (bits 4:3) together.
248#[derive(Clone, Copy, PartialEq, Eq, Debug)]
249#[cfg_attr(feature = "defmt", derive(defmt::Format))]
250pub enum DlhDlmAccOdr {
251    PowerDown,
252    Hz50,
253    Hz100,
254    Hz400,
255    Hz1000,
256}
257
258impl DlhDlmAccOdr {
259    /// `PM[2:0]` + `DR[1:0]` field mask in `CTRL_REG1_A` (bits 7:3).
260    const MASK: u8 = 0b1111_1000;
261
262    fn bits(self) -> u8 {
263        // PM = 001 (normal) with the DR field, except PowerDown = PM 000.
264        match self {
265            DlhDlmAccOdr::PowerDown => 0b000_00 << 3,
266            DlhDlmAccOdr::Hz50 => 0b001_00 << 3,
267            DlhDlmAccOdr::Hz100 => 0b001_01 << 3,
268            DlhDlmAccOdr::Hz400 => 0b001_10 << 3,
269            DlhDlmAccOdr::Hz1000 => 0b001_11 << 3,
270        }
271    }
272}
273
274/// Accelerometer output data rate for the DLHC (`ODR[3:0]` in `CTRL_REG1_A`).
275#[derive(Clone, Copy, PartialEq, Eq, Debug)]
276#[cfg_attr(feature = "defmt", derive(defmt::Format))]
277pub enum DlhcAccOdr {
278    PowerDown,
279    Hz1,
280    Hz10,
281    Hz25,
282    Hz50,
283    Hz100,
284    Hz200,
285    Hz400,
286}
287
288impl DlhcAccOdr {
289    /// `ODR[3:0]` field mask in `CTRL_REG1_A` (bits 7:4).
290    const MASK: u8 = 0b1111_0000;
291
292    fn bits(self) -> u8 {
293        match self {
294            DlhcAccOdr::PowerDown => 0b0000 << 4,
295            DlhcAccOdr::Hz1 => 0b0001 << 4,
296            DlhcAccOdr::Hz10 => 0b0010 << 4,
297            DlhcAccOdr::Hz25 => 0b0011 << 4,
298            DlhcAccOdr::Hz50 => 0b0100 << 4,
299            DlhcAccOdr::Hz100 => 0b0101 << 4,
300            DlhcAccOdr::Hz200 => 0b0110 << 4,
301            DlhcAccOdr::Hz400 => 0b0111 << 4,
302        }
303    }
304}
305
306/// Accelerometer output data rate for the LSM303D (`AODR[3:0]` in `CTRL1`).
307#[derive(Clone, Copy, PartialEq, Eq, Debug)]
308#[cfg_attr(feature = "defmt", derive(defmt::Format))]
309pub enum DAccOdr {
310    PowerDown,
311    Hz3_125,
312    Hz6_25,
313    Hz12_5,
314    Hz25,
315    Hz50,
316    Hz100,
317    Hz200,
318    Hz400,
319    Hz800,
320    Hz1600,
321}
322
323impl DAccOdr {
324    /// `AODR[3:0]` field mask in `CTRL1` (bits 7:4).
325    const MASK: u8 = 0b1111_0000;
326
327    fn bits(self) -> u8 {
328        match self {
329            DAccOdr::PowerDown => 0b0000 << 4,
330            DAccOdr::Hz3_125 => 0b0001 << 4,
331            DAccOdr::Hz6_25 => 0b0010 << 4,
332            DAccOdr::Hz12_5 => 0b0011 << 4,
333            DAccOdr::Hz25 => 0b0100 << 4,
334            DAccOdr::Hz50 => 0b0101 << 4,
335            DAccOdr::Hz100 => 0b0110 << 4,
336            DAccOdr::Hz200 => 0b0111 << 4,
337            DAccOdr::Hz400 => 0b1000 << 4,
338            DAccOdr::Hz800 => 0b1001 << 4,
339            DAccOdr::Hz1600 => 0b1010 << 4,
340        }
341    }
342}
343
344/// Magnetometer output data rate for the DLH (`DO[2:0]` in `CRA_REG_M`).
345///
346/// The DLH caps at 75 Hz (`DO = 111` is "not used", DLH datasheet Table 58).
347/// The DLM and DLHC additionally support 220 Hz — see [`DlmDlhcMagOdr`].
348#[derive(Clone, Copy, PartialEq, Eq, Debug)]
349#[cfg_attr(feature = "defmt", derive(defmt::Format))]
350pub enum DlhMagOdr {
351    Hz0_75,
352    Hz1_5,
353    Hz3,
354    Hz7_5,
355    Hz15,
356    Hz30,
357    Hz75,
358}
359
360impl DlhMagOdr {
361    /// `DO[2:0]` field mask in `CRA_REG_M` (bits 4:2).
362    const MASK: u8 = 0b0001_1100;
363
364    fn bits(self) -> u8 {
365        match self {
366            DlhMagOdr::Hz0_75 => 0b000 << 2,
367            DlhMagOdr::Hz1_5 => 0b001 << 2,
368            DlhMagOdr::Hz3 => 0b010 << 2,
369            DlhMagOdr::Hz7_5 => 0b011 << 2,
370            DlhMagOdr::Hz15 => 0b100 << 2,
371            DlhMagOdr::Hz30 => 0b101 << 2,
372            DlhMagOdr::Hz75 => 0b110 << 2,
373        }
374    }
375}
376
377/// Magnetometer output data rate for the DLM and DLHC (`DO[2:0]` in `CRA_REG_M`).
378///
379/// Same table as the DLH plus 220 Hz at `DO = 111` (verified against the
380/// LSM303DLM datasheet, Table 56, and the LSM303DLHC datasheet, Table 72).
381#[derive(Clone, Copy, PartialEq, Eq, Debug)]
382#[cfg_attr(feature = "defmt", derive(defmt::Format))]
383pub enum DlmDlhcMagOdr {
384    Hz0_75,
385    Hz1_5,
386    Hz3,
387    Hz7_5,
388    Hz15,
389    Hz30,
390    Hz75,
391    Hz220,
392}
393
394impl DlmDlhcMagOdr {
395    /// `DO[2:0]` field mask in `CRA_REG_M` (bits 4:2).
396    const MASK: u8 = 0b0001_1100;
397
398    fn bits(self) -> u8 {
399        match self {
400            DlmDlhcMagOdr::Hz0_75 => 0b000 << 2,
401            DlmDlhcMagOdr::Hz1_5 => 0b001 << 2,
402            DlmDlhcMagOdr::Hz3 => 0b010 << 2,
403            DlmDlhcMagOdr::Hz7_5 => 0b011 << 2,
404            DlmDlhcMagOdr::Hz15 => 0b100 << 2,
405            DlmDlhcMagOdr::Hz30 => 0b101 << 2,
406            DlmDlhcMagOdr::Hz75 => 0b110 << 2,
407            DlmDlhcMagOdr::Hz220 => 0b111 << 2,
408        }
409    }
410}
411
412/// Magnetometer output data rate for the LSM303D (`M_ODR[2:0]` in `CTRL5`).
413///
414/// 100 Hz is only valid when the accelerometer ODR is above 50 Hz (or in
415/// power-down); see the datasheet.
416#[derive(Clone, Copy, PartialEq, Eq, Debug)]
417#[cfg_attr(feature = "defmt", derive(defmt::Format))]
418pub enum DMagOdr {
419    Hz3_125,
420    Hz6_25,
421    Hz12_5,
422    Hz25,
423    Hz50,
424    Hz100,
425}
426
427impl DMagOdr {
428    /// `M_ODR[2:0]` field mask in `CTRL5` (bits 4:2).
429    const MASK: u8 = 0b0001_1100;
430
431    fn bits(self) -> u8 {
432        match self {
433            DMagOdr::Hz3_125 => 0b000 << 2,
434            DMagOdr::Hz6_25 => 0b001 << 2,
435            DMagOdr::Hz12_5 => 0b010 << 2,
436            DMagOdr::Hz25 => 0b011 << 2,
437            DMagOdr::Hz50 => 0b100 << 2,
438            DMagOdr::Hz100 => 0b101 << 2,
439        }
440    }
441}
442
443/// Chip variant, as a runtime value. Returned by [`AnyLsm303::device`].
444#[derive(Clone, Copy, PartialEq, Eq, Debug)]
445#[cfg_attr(feature = "defmt", derive(defmt::Format))]
446pub enum Device {
447    /// LSM303DLH
448    Dlh,
449    /// LSM303DLM
450    Dlm,
451    /// LSM303DLHC
452    Dlhc,
453    /// LSM303D
454    D,
455}
456
457/// State of the chip's SA0 pin, which selects its I²C address.
458///
459/// Ignored on the DLHC, whose addresses are fixed.
460#[derive(Clone, Copy, PartialEq, Eq, Debug)]
461#[cfg_attr(feature = "defmt", derive(defmt::Format))]
462pub enum SA0 {
463    /// SA0 tied to ground.
464    Low,
465    /// SA0 tied to supply.
466    High,
467}
468
469/// Errors returned by the driver.
470#[derive(Debug)]
471#[cfg_attr(feature = "defmt", derive(defmt::Format))]
472pub enum Error<E> {
473    /// Error from the underlying I²C bus.
474    I2c(E),
475    /// Detection found no LSM303 on the bus.
476    DeviceNotFound,
477}
478
479/// A 3-axis reading (accelerometer or magnetometer), in raw sensor counts.
480#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
481#[cfg_attr(feature = "defmt", derive(defmt::Format))]
482pub struct Vector {
483    /// X axis.
484    pub x: i16,
485    /// Y axis.
486    pub y: i16,
487    /// Z axis.
488    pub z: i16,
489}
490
491/// I²C addresses and WHO_AM_I IDs used only for device detection.
492mod detect {
493    pub const D_SA0_HIGH: u8 = 0x1D; // 0b0011101
494    pub const D_SA0_LOW: u8 = 0x1E; // 0b0011110
495    pub const DLX_ACC_SA0_HIGH: u8 = 0x19; // 0b0011001
496    pub const DLX_ACC_SA0_LOW: u8 = 0x18; // 0b0011000
497    pub const DLX_MAG: u8 = 0x1E; // 0b0011110
498
499    pub const WHO_ID_D: u8 = 0x49;
500    pub const WHO_ID_DLM: u8 = 0x3C;
501}
502/// Marker type for the LSM303DLH, used as `Lsm303<I2C, Dlh>`.
503pub struct Dlh;
504/// Marker type for the LSM303DLM, used as `Lsm303<I2C, Dlm>`.
505pub struct Dlm;
506/// Marker type for the LSM303DLHC, used as `Lsm303<I2C, Dlhc>`.
507pub struct Dlhc;
508/// Marker type for the LSM303D, used as `Lsm303<I2C, D>`.
509pub struct D;
510
511/// Marker for the DLH/DLM/DLHC family, which share the magnetometer full-scale
512/// (`GN`) table and register layout. Gates methods common to those three.
513pub trait Dlx: Variant {}
514impl Dlx for Dlh {}
515impl Dlx for Dlm {}
516impl Dlx for Dlhc {}
517
518/// Per-variant hardware differences: I²C addresses, magnetometer output
519/// layout, and the power-on default configuration. Implemented by the marker
520/// types [`Dlh`], [`Dlm`], [`Dlhc`], and [`D`].
521///
522/// This replaces the Arduino library's runtime `translated_regs` table and
523/// `_device` switches: each chip's quirks live in its trait impl and are
524/// resolved at compile time.
525// The returned futures are only awaited inside this crate / on a single-core
526// embassy executor, so `Send` bounds are unnecessary. Same choice as
527// `embedded-hal-async` makes for its own traits.
528#[allow(async_fn_in_trait)]
529#[maybe_async_cfg::maybe(sync(feature = "sync", keep_self), async(feature = "async", keep_self))]
530pub trait Variant: Sized {
531    /// The runtime [`Device`] this marker type corresponds to.
532    ///
533    /// Lets a runtime detection result be checked against the compile-time
534    /// variant; see [`AnyLsm303::into_driver`].
535    const DEVICE: Device;
536
537    /// First register of a 6-byte magnetometer burst read, with the
538    /// auto-increment bit already set where the chip requires it.
539    const MAG_OUT_START: u8;
540
541    /// Accelerometer I²C address for the given SA0 state.
542    fn acc_address(sa0: SA0) -> u8;
543
544    /// Magnetometer I²C address for the given SA0 state.
545    fn mag_address(sa0: SA0) -> u8;
546
547    /// Reassemble the 6 magnetometer bytes (in this chip's output order)
548    /// into a signed X/Y/Z vector.
549    fn parse_mag(buf: &[u8; 6]) -> Vector;
550
551    /// Apply the power-on default configuration:
552    /// enable both sensors at their datasheet-specified
553    /// output data rates and full scales.
554    async fn enable_default<I2C: I2c>(dev: &mut Lsm303<I2C, Self>)
555    -> Result<(), Error<I2C::Error>>;
556}
557#[maybe_async_cfg::maybe(sync(feature = "sync", keep_self), async(feature = "async", keep_self))]
558impl Variant for D {
559    const DEVICE: Device = Device::D;
560
561    // D returns X_L, X_H, Y_L, Y_H, Z_L, Z_H, and needs the auto-increment bit.
562    const MAG_OUT_START: u8 = 0x08 | 0x80; // D_OUT_X_L_M | auto-increment
563
564    fn acc_address(sa0: SA0) -> u8 {
565        match sa0 {
566            SA0::High => detect::D_SA0_HIGH,
567            SA0::Low => detect::D_SA0_LOW,
568        }
569    }
570
571    // On the D the accelerometer and magnetometer share one address.
572    fn mag_address(sa0: SA0) -> u8 {
573        Self::acc_address(sa0)
574    }
575
576    fn parse_mag(buf: &[u8; 6]) -> Vector {
577        Vector {
578            x: i16::from_le_bytes([buf[0], buf[1]]),
579            y: i16::from_le_bytes([buf[2], buf[3]]),
580            z: i16::from_le_bytes([buf[4], buf[5]]),
581        }
582    }
583
584    async fn enable_default<I2C: I2c>(
585        dev: &mut Lsm303<I2C, Self>,
586    ) -> Result<(), Error<I2C::Error>> {
587        // acc_address == mag_address on the D, so either accessor works.
588        dev.write_mag_reg(reg_addr::CTRL2, 0x00).await?; // accel +/-2 g
589        dev.write_mag_reg(reg_addr::CTRL1, 0x57).await?; // accel 50 Hz, all axes on
590        dev.write_mag_reg(reg_addr::CTRL5, 0x64).await?; // mag high-res, 6.25 Hz
591        dev.write_mag_reg(reg_addr::CTRL6, 0x20).await?; // mag +/-4 gauss
592        dev.write_mag_reg(reg_addr::CTRL7, 0x00).await?; // mag continuous-conversion
593        Ok(())
594    }
595}
596#[maybe_async_cfg::maybe(sync(feature = "sync", keep_self), async(feature = "async", keep_self))]
597impl Variant for Dlhc {
598    const DEVICE: Device = Device::Dlhc;
599
600    // DLHC returns X_H, X_L, Z_H, Z_L, Y_H, Y_L; its mag auto-increments on its own.
601    const MAG_OUT_START: u8 = 0x03; // DLHC_OUT_X_H_M
602
603    fn acc_address(_sa0: SA0) -> u8 {
604        detect::DLX_ACC_SA0_HIGH // fixed; the DLHC has no configurable SA0
605    }
606
607    fn mag_address(_sa0: SA0) -> u8 {
608        detect::DLX_MAG
609    }
610
611    fn parse_mag(buf: &[u8; 6]) -> Vector {
612        Vector {
613            x: i16::from_le_bytes([buf[1], buf[0]]),
614            z: i16::from_le_bytes([buf[3], buf[2]]),
615            y: i16::from_le_bytes([buf[5], buf[4]]),
616        }
617    }
618
619    async fn enable_default<I2C: I2c>(
620        dev: &mut Lsm303<I2C, Self>,
621    ) -> Result<(), Error<I2C::Error>> {
622        dev.write_acc_reg(reg_addr::CTRL_REG4_A, 0x08).await?; // +/-2 g, high-res
623        dev.write_acc_reg(reg_addr::CTRL_REG1_A, 0x47).await?; // 50 Hz, all axes on
624        dev.write_mag_reg(reg_addr::CRA_REG_M, 0x0C).await?; // 7.5 Hz
625        dev.write_mag_reg(reg_addr::CRB_REG_M, 0x20).await?; // +/-1.3 gauss
626        dev.write_mag_reg(reg_addr::MR_REG_M, 0x00).await?; // continuous-conversion
627        Ok(())
628    }
629}
630#[maybe_async_cfg::maybe(sync(feature = "sync", keep_self), async(feature = "async", keep_self))]
631impl Variant for Dlm {
632    const DEVICE: Device = Device::Dlm;
633
634    // DLM returns X_H, X_L, Z_H, Z_L, Y_H, Y_L (same order as DLHC).
635    const MAG_OUT_START: u8 = 0x03; // DLM_OUT_X_H_M
636
637    fn acc_address(sa0: SA0) -> u8 {
638        match sa0 {
639            SA0::High => detect::DLX_ACC_SA0_HIGH,
640            SA0::Low => detect::DLX_ACC_SA0_LOW,
641        }
642    }
643
644    fn mag_address(_sa0: SA0) -> u8 {
645        detect::DLX_MAG
646    }
647
648    fn parse_mag(buf: &[u8; 6]) -> Vector {
649        Vector {
650            x: i16::from_le_bytes([buf[1], buf[0]]),
651            z: i16::from_le_bytes([buf[3], buf[2]]),
652            y: i16::from_le_bytes([buf[5], buf[4]]),
653        }
654    }
655
656    async fn enable_default<I2C: I2c>(
657        dev: &mut Lsm303<I2C, Self>,
658    ) -> Result<(), Error<I2C::Error>> {
659        dev.write_acc_reg(reg_addr::CTRL_REG4_A, 0x00).await?; // +/-2 g
660        dev.write_acc_reg(reg_addr::CTRL_REG1_A, 0x27).await?; // normal, 50 Hz, all axes
661        dev.write_mag_reg(reg_addr::CRA_REG_M, 0x0C).await?;
662        dev.write_mag_reg(reg_addr::CRB_REG_M, 0x20).await?;
663        dev.write_mag_reg(reg_addr::MR_REG_M, 0x00).await?;
664        Ok(())
665    }
666}
667#[maybe_async_cfg::maybe(sync(feature = "sync", keep_self), async(feature = "async", keep_self))]
668impl Variant for Dlh {
669    const DEVICE: Device = Device::Dlh;
670
671    // DLH returns X_H, X_L, Y_H, Y_L, Z_H, Z_L (Y before Z, unlike DLM/DLHC).
672    const MAG_OUT_START: u8 = 0x03; // DLH_OUT_X_H_M
673
674    fn acc_address(sa0: SA0) -> u8 {
675        match sa0 {
676            SA0::High => detect::DLX_ACC_SA0_HIGH,
677            SA0::Low => detect::DLX_ACC_SA0_LOW,
678        }
679    }
680
681    fn mag_address(_sa0: SA0) -> u8 {
682        detect::DLX_MAG
683    }
684
685    fn parse_mag(buf: &[u8; 6]) -> Vector {
686        Vector {
687            x: i16::from_le_bytes([buf[1], buf[0]]),
688            y: i16::from_le_bytes([buf[3], buf[2]]),
689            z: i16::from_le_bytes([buf[5], buf[4]]),
690        }
691    }
692
693    async fn enable_default<I2C: I2c>(
694        dev: &mut Lsm303<I2C, Self>,
695    ) -> Result<(), Error<I2C::Error>> {
696        dev.write_acc_reg(reg_addr::CTRL_REG4_A, 0x00).await?;
697        dev.write_acc_reg(reg_addr::CTRL_REG1_A, 0x27).await?;
698        dev.write_mag_reg(reg_addr::CRA_REG_M, 0x0C).await?;
699        dev.write_mag_reg(reg_addr::CRB_REG_M, 0x20).await?;
700        dev.write_mag_reg(reg_addr::MR_REG_M, 0x00).await?;
701        Ok(())
702    }
703}
704
705/// Result of probing the bus: which chip was found and its SA0 state.
706///
707/// Get one from [`AnyLsm303::detect`], then turn it into a typed driver with
708/// [`AnyLsm303::into_driver`].
709pub struct AnyLsm303 {
710    device: Device,
711    sa0: SA0,
712}
713
714#[maybe_async_cfg::maybe(sync(feature = "sync", keep_self), async(feature = "async", keep_self))]
715impl AnyLsm303 {
716    /// Probe the bus for an LSM303.
717    ///
718    /// Pass `Some` for `device` and/or `sa0` to restrict the search; with both
719    /// set, the bus is not probed at all.
720    ///
721    /// # DLHC vs DLM
722    ///
723    /// The DLHC and DLM cannot be told apart reliably. The DLHC answers the
724    /// magnetometer `WHO_AM_I` with the DLM's ID (undocumented in its
725    /// datasheet), and its accelerometer uses the same address as a DLM with
726    /// SA0 high. Following Pololu's library, a chip with that ID is reported
727    /// as a DLHC when found at the SA0-high address and as a DLM at SA0-low.
728    /// A DLM with SA0 pulled high is therefore detected as a DLHC; pass
729    /// `Some(Device::Dlm)` to avoid this.
730    pub async fn detect<I2C: I2c>(
731        i2c: &mut I2C,
732        device: Option<Device>,
733        sa0: Option<SA0>,
734    ) -> Result<Self, Error<I2C::Error>> {
735        Self::probe(i2c, device, sa0).await
736    }
737
738    /// Probe the bus to resolve the device type and SA0 state.
739    ///
740    /// Ported from Pololu's `LSM303::init` detection logic.
741    async fn probe<I2C: I2c>(
742        i2c: &mut I2C,
743        device: Option<Device>,
744        sa0: Option<SA0>,
745    ) -> Result<Self, Error<I2C::Error>> {
746        // Fully specified → trust the caller, don't probe.
747        if let (Some(d), Some(s)) = (device, sa0) {
748            return Ok(AnyLsm303 { device: d, sa0: s });
749        }
750
751        // LSM303D
752        if device.is_none() || device == Some(Device::D) {
753            if sa0 != Some(SA0::Low)
754                && Self::test_reg(i2c, detect::D_SA0_HIGH, reg_addr::WHO_AM_I).await?
755                    == Some(detect::WHO_ID_D)
756            {
757                return Ok(AnyLsm303 {
758                    device: Device::D,
759                    sa0: SA0::High,
760                });
761            }
762            if sa0 != Some(SA0::High)
763                && Self::test_reg(i2c, detect::D_SA0_LOW, reg_addr::WHO_AM_I).await?
764                    == Some(detect::WHO_ID_D)
765            {
766                return Ok(AnyLsm303 {
767                    device: Device::D,
768                    sa0: SA0::Low,
769                });
770            }
771        }
772
773        // LSM303DLHC / DLM / DLH
774        let is_dlx = matches!(
775            device,
776            None | Some(Device::Dlhc) | Some(Device::Dlm) | Some(Device::Dlh)
777        );
778        if is_dlx {
779            if sa0 != Some(SA0::Low)
780                && Self::test_reg(i2c, detect::DLX_ACC_SA0_HIGH, reg_addr::CTRL_REG1_A)
781                    .await?
782                    .is_some()
783            {
784                // Keep the caller's device if pinned; otherwise disambiguate by mag ID.
785                // DLHC reports the DLM mag ID, so a match here means DLHC.
786                let dev = match device {
787                    Some(d) => d,
788                    None if Self::mag_is_dlm(i2c).await? => Device::Dlhc,
789                    None => Device::Dlh,
790                };
791                return Ok(AnyLsm303 {
792                    device: dev,
793                    sa0: SA0::High,
794                });
795            }
796            if sa0 != Some(SA0::High)
797                && Self::test_reg(i2c, detect::DLX_ACC_SA0_LOW, reg_addr::CTRL_REG1_A)
798                    .await?
799                    .is_some()
800            {
801                let dev = match device {
802                    Some(d) => d,
803                    None if Self::mag_is_dlm(i2c).await? => Device::Dlm,
804                    None => Device::Dlh,
805                };
806                return Ok(AnyLsm303 {
807                    device: dev,
808                    sa0: SA0::Low,
809                });
810            }
811        }
812
813        Err(Error::DeviceNotFound)
814    }
815
816    /// True if the magnetometer reports the DLM WHO_AM_I ID.
817    async fn mag_is_dlm<I2C: I2c>(i2c: &mut I2C) -> Result<bool, Error<I2C::Error>> {
818        Ok(
819            Self::test_reg(i2c, detect::DLX_MAG, reg_addr::WHO_AM_I_M).await?
820                == Some(detect::WHO_ID_DLM),
821        )
822    }
823
824    /// Read one register at `address`.
825    ///
826    /// `Ok(None)` means the device didn't ACK (i.e. nothing is at that
827    /// address); real bus faults propagate as `Err`.
828    async fn test_reg<I2C: I2c>(
829        i2c: &mut I2C,
830        address: u8,
831        register: u8,
832    ) -> Result<Option<u8>, Error<I2C::Error>> {
833        let mut buf = [0u8];
834        // i2c.write_read(0x1d, &[0x0f], &mut who).unwrap();
835        // info!("WHO_AM_I = 0x{:02x} (expect 0x49 for LSM303D)", who[0]);
836
837        match i2c.write_read(address, &[register], &mut buf).await {
838            Ok(()) => Ok(Some(buf[0])),
839            Err(e) => match e.kind() {
840                ErrorKind::NoAcknowledge(_) => Ok(None),
841                _ => Err(Error::I2c(e)),
842            },
843        }
844    }
845}
846
847impl AnyLsm303 {
848    /// The device type that was detected.
849    pub fn device(&self) -> Device {
850        self.device
851    }
852
853    /// The SA0 state that was detected.
854    pub fn sa0(&self) -> SA0 {
855        self.sa0
856    }
857
858    /// Turn a detection result into a typed driver, taking ownership of the bus.
859    pub fn into_driver<I2C: I2c, V: Variant>(self, i2c: I2C) -> Result<Lsm303<I2C, V>, Device> {
860        if self.device != V::DEVICE {
861            return Err(self.device);
862        }
863        Ok(Lsm303::new_typed(i2c, self.sa0))
864    }
865}
866
867/// Driver for one LSM303 chip on an I²C bus.
868///
869/// `V` is the chip variant ([`Dlh`], [`Dlm`], [`Dlhc`] or [`D`]); it selects
870/// the addresses, register layout and which settings are available. Create one
871/// with `Lsm303::<_, D>::new(i2c, sa0)` (or the matching variant), or from a
872/// detection result with [`AnyLsm303::into_driver`].
873pub struct Lsm303<I2C, V> {
874    _variant: PhantomData<V>,
875    i2c: I2C,
876    sa0: SA0,
877}
878
879impl<I2C: I2c, V> Lsm303<I2C, V> {
880    /// Wrap an already-identified device.
881    ///
882    /// Internal: used by [`AnyLsm303::detect`] and the per-variant
883    /// constructors once the variant `V` is known.
884    fn new_typed(i2c: I2C, sa0: SA0) -> Self {
885        Self {
886            _variant: PhantomData,
887            i2c,
888            sa0,
889        }
890    }
891
892    /// Consume the driver and release the underlying I²C bus.
893    pub fn release(self) -> I2C {
894        self.i2c
895    }
896}
897
898// Direct constructors that skip detection, use when you already know which
899// chip is on the bus. Only the variant you name is monomorphized, so unused
900// variants are stripped from the binary.
901impl<I2C: I2c> Lsm303<I2C, Dlh> {
902    /// Create a driver for an LSM303DLH at the given SA0 address.
903    pub fn new(i2c: I2C, sa0: SA0) -> Self {
904        Self::new_typed(i2c, sa0)
905    }
906}
907
908impl<I2C: I2c> Lsm303<I2C, Dlm> {
909    /// Create a driver for an LSM303DLM at the given SA0 address.
910    pub fn new(i2c: I2C, sa0: SA0) -> Self {
911        Self::new_typed(i2c, sa0)
912    }
913}
914
915impl<I2C: I2c> Lsm303<I2C, Dlhc> {
916    /// Create a driver for an LSM303DLHC at the given SA0 address.
917    pub fn new(i2c: I2C, sa0: SA0) -> Self {
918        Self::new_typed(i2c, sa0)
919    }
920}
921
922impl<I2C: I2c> Lsm303<I2C, D> {
923    /// Create a driver for an LSM303D at the given SA0 address.
924    pub fn new(i2c: I2C, sa0: SA0) -> Self {
925        Self::new_typed(i2c, sa0)
926    }
927}
928
929// Operational methods, available once the variant `V` is known.
930#[maybe_async_cfg::maybe(sync(feature = "sync", keep_self), async(feature = "async", keep_self))]
931impl<I2C: I2c, V: Variant> Lsm303<I2C, V> {
932    /// Write `value` to `reg` at the given I²C `address`.
933    async fn write_register(
934        &mut self,
935        address: u8,
936        reg: u8,
937        value: u8,
938    ) -> Result<(), Error<I2C::Error>> {
939        self.i2c
940            .write(address, &[reg, value])
941            .await
942            .map_err(Error::I2c)
943    }
944
945    /// Read one register at the given I²C `address`.
946    async fn read_register(&mut self, address: u8, reg: u8) -> Result<u8, Error<I2C::Error>> {
947        let mut buf = [0u8; 1];
948        self.i2c
949            .write_read(address, &[reg], &mut buf)
950            .await
951            .map_err(Error::I2c)?;
952        Ok(buf[0])
953    }
954
955    /// Write to an accelerometer register.
956    pub async fn write_acc_reg(&mut self, reg: u8, value: u8) -> Result<(), Error<I2C::Error>> {
957        let address = V::acc_address(self.sa0);
958        self.write_register(address, reg, value).await
959    }
960
961    /// Read an accelerometer register.
962    pub async fn read_acc_reg(&mut self, reg: u8) -> Result<u8, Error<I2C::Error>> {
963        let address = V::acc_address(self.sa0);
964        self.read_register(address, reg).await
965    }
966
967    /// Write to a magnetometer register.
968    pub async fn write_mag_reg(&mut self, reg: u8, value: u8) -> Result<(), Error<I2C::Error>> {
969        let address = V::mag_address(self.sa0);
970        self.write_register(address, reg, value).await
971    }
972
973    /// Read a magnetometer register.
974    pub async fn read_mag_reg(&mut self, reg: u8) -> Result<u8, Error<I2C::Error>> {
975        let address = V::mag_address(self.sa0);
976        self.read_register(address, reg).await
977    }
978
979    /// Apply the power-on default configuration for this variant.
980    pub async fn enable_default(&mut self) -> Result<(), Error<I2C::Error>> {
981        V::enable_default(self).await
982    }
983
984    /// Read the three accelerometer axes.
985    pub async fn read_accel(&mut self) -> Result<Vector, Error<I2C::Error>> {
986        let address = V::acc_address(self.sa0);
987        let mut buf = [0u8; 6];
988        // The MSB of the sub-address enables auto-increment for the burst read.
989        self.i2c
990            .write_read(address, &[reg_addr::OUT_X_L_A | 0x80], &mut buf)
991            .await
992            .map_err(Error::I2c)?;
993        // Accelerometer output is X_L, X_H, Y_L, Y_H, Z_L, Z_H on every variant.
994        Ok(Vector {
995            x: i16::from_le_bytes([buf[0], buf[1]]),
996            y: i16::from_le_bytes([buf[2], buf[3]]),
997            z: i16::from_le_bytes([buf[4], buf[5]]),
998        })
999    }
1000
1001    /// Read the three magnetometer axes.
1002    pub async fn read_mag(&mut self) -> Result<Vector, Error<I2C::Error>> {
1003        let address = V::mag_address(self.sa0);
1004        let mut buf = [0u8; 6];
1005        self.i2c
1006            .write_read(address, &[V::MAG_OUT_START], &mut buf)
1007            .await
1008            .map_err(Error::I2c)?;
1009        Ok(V::parse_mag(&buf))
1010    }
1011
1012    /// Read both the accelerometer and magnetometer.
1013    pub async fn read(&mut self) -> Result<(Vector, Vector), Error<I2C::Error>> {
1014        Ok((self.read_accel().await?, self.read_mag().await?))
1015    }
1016
1017    /// Read-modify-write the `mask` bits of an accelerometer register, leaving
1018    /// the other bits untouched.
1019    async fn modify_acc_reg(
1020        &mut self,
1021        reg: u8,
1022        mask: u8,
1023        bits: u8,
1024    ) -> Result<(), Error<I2C::Error>> {
1025        let current = self.read_acc_reg(reg).await?;
1026        self.write_acc_reg(reg, (current & !mask) | (bits & mask))
1027            .await
1028    }
1029
1030    /// Read-modify-write the `mask` bits of a magnetometer register.
1031    async fn modify_mag_reg(
1032        &mut self,
1033        reg: u8,
1034        mask: u8,
1035        bits: u8,
1036    ) -> Result<(), Error<I2C::Error>> {
1037        let current = self.read_mag_reg(reg).await?;
1038        self.write_mag_reg(reg, (current & !mask) | (bits & mask))
1039            .await
1040    }
1041}
1042
1043// Accelerometer full-scale, gated per variant: each chip accepts only its own
1044// range set, and the D uses a different register/field than the DLx trio.
1045#[maybe_async_cfg::maybe(sync(feature = "sync", keep_self), async(feature = "async", keep_self))]
1046impl<I2C: I2c> Lsm303<I2C, Dlh> {
1047    /// Set the accelerometer full-scale range.
1048    pub async fn set_accel_scale(
1049        &mut self,
1050        scale: DlhDlmAccScale,
1051    ) -> Result<(), Error<I2C::Error>> {
1052        self.modify_acc_reg(reg_addr::CTRL_REG4_A, DlhDlmAccScale::MASK, scale.bits())
1053            .await
1054    }
1055
1056    /// Set the accelerometer output data rate (also sets normal power mode).
1057    pub async fn set_accel_odr(&mut self, odr: DlhDlmAccOdr) -> Result<(), Error<I2C::Error>> {
1058        self.modify_acc_reg(reg_addr::CTRL_REG1_A, DlhDlmAccOdr::MASK, odr.bits())
1059            .await
1060    }
1061
1062    /// Set the magnetometer output data rate (`DO` in `CRA_REG_M`).
1063    pub async fn set_mag_odr(&mut self, odr: DlhMagOdr) -> Result<(), Error<I2C::Error>> {
1064        self.modify_mag_reg(reg_addr::CRA_REG_M, DlhMagOdr::MASK, odr.bits())
1065            .await
1066    }
1067
1068    /// Read back the currently configured accelerometer full-scale range.
1069    pub async fn read_accel_scale(&mut self) -> Result<DlhDlmAccScale, Error<I2C::Error>> {
1070        let reg = self.read_acc_reg(reg_addr::CTRL_REG4_A).await?;
1071        Ok(DlhDlmAccScale::from_reg(reg))
1072    }
1073}
1074#[maybe_async_cfg::maybe(sync(feature = "sync", keep_self), async(feature = "async", keep_self))]
1075impl<I2C: I2c> Lsm303<I2C, Dlm> {
1076    /// Set the accelerometer full-scale range.
1077    pub async fn set_accel_scale(
1078        &mut self,
1079        scale: DlhDlmAccScale,
1080    ) -> Result<(), Error<I2C::Error>> {
1081        self.modify_acc_reg(reg_addr::CTRL_REG4_A, DlhDlmAccScale::MASK, scale.bits())
1082            .await
1083    }
1084
1085    /// Set the accelerometer output data rate (also sets normal power mode).
1086    pub async fn set_accel_odr(&mut self, odr: DlhDlmAccOdr) -> Result<(), Error<I2C::Error>> {
1087        self.modify_acc_reg(reg_addr::CTRL_REG1_A, DlhDlmAccOdr::MASK, odr.bits())
1088            .await
1089    }
1090
1091    /// Set the magnetometer output data rate, including 220 Hz.
1092    pub async fn set_mag_odr(&mut self, odr: DlmDlhcMagOdr) -> Result<(), Error<I2C::Error>> {
1093        self.modify_mag_reg(reg_addr::CRA_REG_M, DlmDlhcMagOdr::MASK, odr.bits())
1094            .await
1095    }
1096
1097    /// Read back the currently configured accelerometer full-scale range.
1098    pub async fn read_accel_scale(&mut self) -> Result<DlhDlmAccScale, Error<I2C::Error>> {
1099        let reg = self.read_acc_reg(reg_addr::CTRL_REG4_A).await?;
1100        Ok(DlhDlmAccScale::from_reg(reg))
1101    }
1102}
1103#[maybe_async_cfg::maybe(sync(feature = "sync", keep_self), async(feature = "async", keep_self))]
1104impl<I2C: I2c> Lsm303<I2C, Dlhc> {
1105    /// Set the accelerometer full-scale range.
1106    pub async fn set_accel_scale(&mut self, scale: DlhcAccScale) -> Result<(), Error<I2C::Error>> {
1107        self.modify_acc_reg(reg_addr::CTRL_REG4_A, DlhcAccScale::MASK, scale.bits())
1108            .await
1109    }
1110
1111    /// Set the accelerometer output data rate.
1112    pub async fn set_accel_odr(&mut self, odr: DlhcAccOdr) -> Result<(), Error<I2C::Error>> {
1113        self.modify_acc_reg(reg_addr::CTRL_REG1_A, DlhcAccOdr::MASK, odr.bits())
1114            .await
1115    }
1116
1117    /// Set the magnetometer output data rate, including 220 Hz.
1118    pub async fn set_mag_odr(&mut self, odr: DlmDlhcMagOdr) -> Result<(), Error<I2C::Error>> {
1119        self.modify_mag_reg(reg_addr::CRA_REG_M, DlmDlhcMagOdr::MASK, odr.bits())
1120            .await
1121    }
1122
1123    /// Read back the currently configured accelerometer full-scale range.
1124    pub async fn read_accel_scale(&mut self) -> Result<DlhcAccScale, Error<I2C::Error>> {
1125        let reg = self.read_acc_reg(reg_addr::CTRL_REG4_A).await?;
1126        Ok(DlhcAccScale::from_reg(reg))
1127    }
1128}
1129#[maybe_async_cfg::maybe(sync(feature = "sync", keep_self), async(feature = "async", keep_self))]
1130impl<I2C: I2c> Lsm303<I2C, D> {
1131    /// Set the accelerometer full-scale range (`AFS` in `CTRL2`).
1132    pub async fn set_accel_scale(&mut self, scale: DAccScale) -> Result<(), Error<I2C::Error>> {
1133        self.modify_acc_reg(reg_addr::CTRL2, DAccScale::MASK, scale.bits())
1134            .await
1135    }
1136
1137    /// Set the accelerometer output data rate (`AODR` in `CTRL1`).
1138    pub async fn set_accel_odr(&mut self, odr: DAccOdr) -> Result<(), Error<I2C::Error>> {
1139        self.modify_acc_reg(reg_addr::CTRL1, DAccOdr::MASK, odr.bits())
1140            .await
1141    }
1142
1143    /// Set the magnetometer full-scale range (`MFS` in `CTRL6`).
1144    pub async fn set_mag_scale(&mut self, scale: DMagScale) -> Result<(), Error<I2C::Error>> {
1145        self.modify_mag_reg(reg_addr::CTRL6, DMagScale::MASK, scale.bits())
1146            .await
1147    }
1148
1149    /// Set the magnetometer output data rate (`M_ODR` in `CTRL5`).
1150    pub async fn set_mag_odr(&mut self, odr: DMagOdr) -> Result<(), Error<I2C::Error>> {
1151        self.modify_mag_reg(reg_addr::CTRL5, DMagOdr::MASK, odr.bits())
1152            .await
1153    }
1154
1155    /// Read back the currently configured accelerometer full-scale range.
1156    pub async fn read_accel_scale(&mut self) -> Result<DAccScale, Error<I2C::Error>> {
1157        let reg = self.read_acc_reg(reg_addr::CTRL2).await?;
1158        Ok(DAccScale::from_reg(reg))
1159    }
1160}
1161
1162// Magnetometer full-scale, shared by the DLH/DLM/DLHC (identical `GN` table).
1163// Mag ODR is *not* shared: the DLM and DLHC support 220 Hz that the DLH lacks,
1164// so its setter lives on the per-variant blocks above.
1165#[maybe_async_cfg::maybe(sync(feature = "sync", keep_self), async(feature = "async", keep_self))]
1166impl<I2C: I2c, V: Dlx> Lsm303<I2C, V> {
1167    /// Set the magnetometer full-scale range.
1168    pub async fn set_mag_scale(&mut self, scale: DlxMagScale) -> Result<(), Error<I2C::Error>> {
1169        self.modify_mag_reg(reg_addr::CRB_REG_M, DlxMagScale::MASK, scale.bits())
1170            .await
1171    }
1172}
1173#[maybe_async_cfg::maybe(sync(feature = "sync", keep_self), async(feature = "async", keep_self))]
1174// The returned futures are only awaited inside this crate / on a single-core
1175// embassy executor, so `Send` bounds are unnecessary. Same choice as
1176// `embedded-hal-async` makes for its own traits.
1177#[allow(async_fn_in_trait)]
1178/// Chips with a built-in temperature sensor (currently only the LSM303D).
1179pub trait HasTemperature<I2C: I2c> {
1180    /// Read the raw temperature: a signed 12-bit value, 8 LSB/°C.
1181    ///
1182    /// The zero point is not calibrated, so this is only useful for relative
1183    /// changes. The sensor must be enabled first (`TEMP_EN` in `CTRL5`).
1184    async fn read_temperature(&mut self) -> Result<i16, Error<I2C::Error>>;
1185}
1186#[maybe_async_cfg::maybe(sync(feature = "sync", keep_self), async(feature = "async", keep_self))]
1187impl<I2C: I2c> HasTemperature<I2C> for Lsm303<I2C, D> {
1188    async fn read_temperature(&mut self) -> Result<i16, Error<I2C::Error>> {
1189        let temp_out_l = self.read_acc_reg(TEMP_OUT_L).await?;
1190        let temp_out_h = self.read_acc_reg(TEMP_OUT_H).await?;
1191        // 12-bit two's complement, right-justified: sign-extend from bit 11.
1192        let raw = i16::from_le_bytes([temp_out_l, temp_out_h]);
1193        Ok((raw << 4) >> 4)
1194    }
1195}