lsm303-driver 0.1.0

no_std driver for the ST LSM303 accelerometer + magnetometer family (GY-511)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
// part how this code is a translation from https://github.com/pololu/lsm303-arduino
//! A `no_std` driver for the ST LSM303 accelerometer + magnetometer family
//! (also sold as the **GY-511** breakout board):
//!
//! - LSM303DLH
//! - LSM303DLM
//! - LSM303DLHC
//! - LSM303D
//!
//! Built on `embedded-hal` 1.0. It is async by default; enable the `sync`
//! feature for the blocking API.
//!
//! # Usage
//!
//! ```ignore
//! use lsm303_driver::{Lsm303, D, SA0};
//!
//! // `i2c` is any `embedded_hal_async::i2c::I2c` implementation.
//! let mut sensor = Lsm303::<_, D>::new(i2c, SA0::High);
//! sensor.enable_default().await?;
//!
//! let (accel, mag) = sensor.read().await?;
//! // accel.x, accel.y, accel.z, mag.x, mag.y, mag.z (raw i16 counts)
//! ```
//!
//! Don't know which chip you have? Let the driver detect it:
//!
//! ```ignore
//! use lsm303_driver::{AnyLsm303, Lsm303, D};
//!
//! let found = AnyLsm303::detect(&mut i2c, None, None).await?;
//!
//! let mut sensor: Lsm303<_, D> = match found.into_driver(i2c) {
//!     Ok(sensor) => sensor,
//!     Err(other) => panic!("expected an LSM303D, found {:?}", other),
//! };
//! sensor.enable_default().await?;
//! ```
//!
//! # Status
//!
//! Tested only on the **LSM303D**. The other variants are implemented from
//! their datasheets but not yet tested on hardware.

#![no_std]

// `sync` and `async` select which `embedded-hal` I2c trait the driver is built
// against, so exactly one must be active. Cargo features are additive, so guard
// against a dependency turning on the other one behind your back.
#[cfg(all(feature = "sync", feature = "async"))]
compile_error!(
    "features `sync` and `async` are mutually exclusive - enable exactly one \
     (e.g. `default-features = false, features = [\"sync\"]`)"
);

#[cfg(not(any(feature = "sync", feature = "async")))]
compile_error!("enable exactly one of the `sync` or `async` features");

mod lsm303_registers;
#[cfg(test)]
mod tests;

use lsm303_registers::*;

use crate::lsm303_registers::reg_addr::{TEMP_OUT_H, TEMP_OUT_L};
use core::marker::PhantomData;
#[cfg(feature = "sync")]
use embedded_hal::i2c::{Error as _, ErrorKind, I2c};
#[cfg(feature = "async")]
use embedded_hal_async::i2c::{Error as _, ErrorKind, I2c};

// Full-scale range enums.
//
// Each `bits()` returns the register field value already shifted into position,
// and `MASK` is that field's bit mask, so a setter does a read-modify-write of
// exactly those bits.
//
// The bit encodings below are verified against the ST datasheets (LSM303DLH,
// LSM303DLHC, LSM303D). Note DLH/DLM encode 8 g as `FS = 0b11` while the DLHC
// uses `0b10`, which is why the accelerometer scales are separate enums.

/// Magnetometer full-scale range for the DLH/DLM/DLHC (`GN[2:0]` in `CRB_REG_M`).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum DlxMagScale {
    G1_3,
    G1_9,
    G2_5,
    G4_0,
    G4_7,
    G5_6,
    G8_1,
}

impl DlxMagScale {
    /// `GN[2:0]` field mask in `CRB_REG_M` (bits 7:5).
    const MASK: u8 = 0b1110_0000;

    fn bits(self) -> u8 {
        match self {
            DlxMagScale::G1_3 => 0b001 << 5,
            DlxMagScale::G1_9 => 0b010 << 5,
            DlxMagScale::G2_5 => 0b011 << 5,
            DlxMagScale::G4_0 => 0b100 << 5,
            DlxMagScale::G4_7 => 0b101 << 5,
            DlxMagScale::G5_6 => 0b110 << 5,
            DlxMagScale::G8_1 => 0b111 << 5,
        }
    }
}

/// Magnetometer full-scale range for the LSM303D (`MFS[1:0]` in `CTRL6`).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum DMagScale {
    G2,
    G4,
    G8,
    G12,
}

impl DMagScale {
    /// `MFS[1:0]` field mask in `CTRL6` (bits 6:5).
    const MASK: u8 = 0b0110_0000;

    fn bits(self) -> u8 {
        match self {
            DMagScale::G2 => 0b00 << 5,
            DMagScale::G4 => 0b01 << 5,
            DMagScale::G8 => 0b10 << 5,
            DMagScale::G12 => 0b11 << 5,
        }
    }
}

/// Accelerometer full-scale range for the DLH and DLM (`FS[1:0]` in `CTRL_REG4_A`).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum DlhDlmAccScale {
    G2,
    G4,
    G8,
}

impl DlhDlmAccScale {
    /// `FS[1:0]` field mask in `CTRL_REG4_A` (bits 5:4).
    const MASK: u8 = 0b0011_0000;

    fn bits(self) -> u8 {
        // NB: DLH/DLM encode 8 g as FS = 0b11 (0b10 is unused).
        match self {
            DlhDlmAccScale::G2 => 0b00 << 4,
            DlhDlmAccScale::G4 => 0b01 << 4,
            DlhDlmAccScale::G8 => 0b11 << 4,
        }
    }

    /// Decode the current range from a raw `CTRL_REG4_A` value.
    fn from_reg(reg: u8) -> Self {
        match reg & Self::MASK {
            0x10 => DlhDlmAccScale::G4,
            0x30 => DlhDlmAccScale::G8,
            _ => DlhDlmAccScale::G2,
        }
    }
}

/// Accelerometer full-scale range for the DLHC (`FS[1:0]` in `CTRL_REG4_A`).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum DlhcAccScale {
    G2,
    G4,
    G8,
    G16,
}

impl DlhcAccScale {
    /// `FS[1:0]` field mask in `CTRL_REG4_A` (bits 5:4).
    const MASK: u8 = 0b0011_0000;

    fn bits(self) -> u8 {
        // NB: the DLHC encodes 8 g as FS = 0b10 (unlike DLH/DLM's 0b11).
        match self {
            DlhcAccScale::G2 => 0b00 << 4,
            DlhcAccScale::G4 => 0b01 << 4,
            DlhcAccScale::G8 => 0b10 << 4,
            DlhcAccScale::G16 => 0b11 << 4,
        }
    }

    /// Decode the current range from a raw `CTRL_REG4_A` value.
    fn from_reg(reg: u8) -> Self {
        match reg & Self::MASK {
            0x10 => DlhcAccScale::G4,
            0x20 => DlhcAccScale::G8,
            0x30 => DlhcAccScale::G16,
            _ => DlhcAccScale::G2,
        }
    }
}

/// Accelerometer full-scale range for the LSM303D (`AFS[2:0]` in `CTRL2`).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum DAccScale {
    G2,
    G4,
    G6,
    G8,
    G16,
}

impl DAccScale {
    /// `AFS[2:0]` field mask in `CTRL2` (bits 5:3).
    const MASK: u8 = 0b0011_1000;

    fn bits(self) -> u8 {
        match self {
            DAccScale::G2 => 0b000 << 3,
            DAccScale::G4 => 0b001 << 3,
            DAccScale::G6 => 0b010 << 3,
            DAccScale::G8 => 0b011 << 3,
            DAccScale::G16 => 0b100 << 3,
        }
    }

    /// Decode the current range from a raw `CTRL2` value.
    fn from_reg(reg: u8) -> Self {
        match reg & Self::MASK {
            0x08 => DAccScale::G4,
            0x10 => DAccScale::G6,
            0x18 => DAccScale::G8,
            0x20 => DAccScale::G16,
            _ => DAccScale::G2,
        }
    }
}

// Output-data-rate enums (verified against the ST datasheets).

/// Accelerometer output data rate for the DLH and DLM (`CTRL_REG1_A`).
///
/// These chips select the rate via the `DR` field but only produce data in
/// normal power mode, so setting a rate also forces `PM = normal`; `PowerDown`
/// sets `PM = power-down`. Encoded across `PM[2:0]` (bits 7:5) and `DR[1:0]`
/// (bits 4:3) together.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum DlhDlmAccOdr {
    PowerDown,
    Hz50,
    Hz100,
    Hz400,
    Hz1000,
}

impl DlhDlmAccOdr {
    /// `PM[2:0]` + `DR[1:0]` field mask in `CTRL_REG1_A` (bits 7:3).
    const MASK: u8 = 0b1111_1000;

    fn bits(self) -> u8 {
        // PM = 001 (normal) with the DR field, except PowerDown = PM 000.
        match self {
            DlhDlmAccOdr::PowerDown => 0b000_00 << 3,
            DlhDlmAccOdr::Hz50 => 0b001_00 << 3,
            DlhDlmAccOdr::Hz100 => 0b001_01 << 3,
            DlhDlmAccOdr::Hz400 => 0b001_10 << 3,
            DlhDlmAccOdr::Hz1000 => 0b001_11 << 3,
        }
    }
}

/// Accelerometer output data rate for the DLHC (`ODR[3:0]` in `CTRL_REG1_A`).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum DlhcAccOdr {
    PowerDown,
    Hz1,
    Hz10,
    Hz25,
    Hz50,
    Hz100,
    Hz200,
    Hz400,
}

impl DlhcAccOdr {
    /// `ODR[3:0]` field mask in `CTRL_REG1_A` (bits 7:4).
    const MASK: u8 = 0b1111_0000;

    fn bits(self) -> u8 {
        match self {
            DlhcAccOdr::PowerDown => 0b0000 << 4,
            DlhcAccOdr::Hz1 => 0b0001 << 4,
            DlhcAccOdr::Hz10 => 0b0010 << 4,
            DlhcAccOdr::Hz25 => 0b0011 << 4,
            DlhcAccOdr::Hz50 => 0b0100 << 4,
            DlhcAccOdr::Hz100 => 0b0101 << 4,
            DlhcAccOdr::Hz200 => 0b0110 << 4,
            DlhcAccOdr::Hz400 => 0b0111 << 4,
        }
    }
}

/// Accelerometer output data rate for the LSM303D (`AODR[3:0]` in `CTRL1`).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum DAccOdr {
    PowerDown,
    Hz3_125,
    Hz6_25,
    Hz12_5,
    Hz25,
    Hz50,
    Hz100,
    Hz200,
    Hz400,
    Hz800,
    Hz1600,
}

impl DAccOdr {
    /// `AODR[3:0]` field mask in `CTRL1` (bits 7:4).
    const MASK: u8 = 0b1111_0000;

    fn bits(self) -> u8 {
        match self {
            DAccOdr::PowerDown => 0b0000 << 4,
            DAccOdr::Hz3_125 => 0b0001 << 4,
            DAccOdr::Hz6_25 => 0b0010 << 4,
            DAccOdr::Hz12_5 => 0b0011 << 4,
            DAccOdr::Hz25 => 0b0100 << 4,
            DAccOdr::Hz50 => 0b0101 << 4,
            DAccOdr::Hz100 => 0b0110 << 4,
            DAccOdr::Hz200 => 0b0111 << 4,
            DAccOdr::Hz400 => 0b1000 << 4,
            DAccOdr::Hz800 => 0b1001 << 4,
            DAccOdr::Hz1600 => 0b1010 << 4,
        }
    }
}

/// Magnetometer output data rate for the DLH (`DO[2:0]` in `CRA_REG_M`).
///
/// The DLH caps at 75 Hz (`DO = 111` is "not used", DLH datasheet Table 58).
/// The DLM and DLHC additionally support 220 Hz — see [`DlmDlhcMagOdr`].
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum DlhMagOdr {
    Hz0_75,
    Hz1_5,
    Hz3,
    Hz7_5,
    Hz15,
    Hz30,
    Hz75,
}

impl DlhMagOdr {
    /// `DO[2:0]` field mask in `CRA_REG_M` (bits 4:2).
    const MASK: u8 = 0b0001_1100;

    fn bits(self) -> u8 {
        match self {
            DlhMagOdr::Hz0_75 => 0b000 << 2,
            DlhMagOdr::Hz1_5 => 0b001 << 2,
            DlhMagOdr::Hz3 => 0b010 << 2,
            DlhMagOdr::Hz7_5 => 0b011 << 2,
            DlhMagOdr::Hz15 => 0b100 << 2,
            DlhMagOdr::Hz30 => 0b101 << 2,
            DlhMagOdr::Hz75 => 0b110 << 2,
        }
    }
}

/// Magnetometer output data rate for the DLM and DLHC (`DO[2:0]` in `CRA_REG_M`).
///
/// Same table as the DLH plus 220 Hz at `DO = 111` (verified against the
/// LSM303DLM datasheet, Table 56, and the LSM303DLHC datasheet, Table 72).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum DlmDlhcMagOdr {
    Hz0_75,
    Hz1_5,
    Hz3,
    Hz7_5,
    Hz15,
    Hz30,
    Hz75,
    Hz220,
}

impl DlmDlhcMagOdr {
    /// `DO[2:0]` field mask in `CRA_REG_M` (bits 4:2).
    const MASK: u8 = 0b0001_1100;

    fn bits(self) -> u8 {
        match self {
            DlmDlhcMagOdr::Hz0_75 => 0b000 << 2,
            DlmDlhcMagOdr::Hz1_5 => 0b001 << 2,
            DlmDlhcMagOdr::Hz3 => 0b010 << 2,
            DlmDlhcMagOdr::Hz7_5 => 0b011 << 2,
            DlmDlhcMagOdr::Hz15 => 0b100 << 2,
            DlmDlhcMagOdr::Hz30 => 0b101 << 2,
            DlmDlhcMagOdr::Hz75 => 0b110 << 2,
            DlmDlhcMagOdr::Hz220 => 0b111 << 2,
        }
    }
}

/// Magnetometer output data rate for the LSM303D (`M_ODR[2:0]` in `CTRL5`).
///
/// 100 Hz is only valid when the accelerometer ODR is above 50 Hz (or in
/// power-down); see the datasheet.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum DMagOdr {
    Hz3_125,
    Hz6_25,
    Hz12_5,
    Hz25,
    Hz50,
    Hz100,
}

impl DMagOdr {
    /// `M_ODR[2:0]` field mask in `CTRL5` (bits 4:2).
    const MASK: u8 = 0b0001_1100;

    fn bits(self) -> u8 {
        match self {
            DMagOdr::Hz3_125 => 0b000 << 2,
            DMagOdr::Hz6_25 => 0b001 << 2,
            DMagOdr::Hz12_5 => 0b010 << 2,
            DMagOdr::Hz25 => 0b011 << 2,
            DMagOdr::Hz50 => 0b100 << 2,
            DMagOdr::Hz100 => 0b101 << 2,
        }
    }
}

/// Chip variant, as a runtime value. Returned by [`AnyLsm303::device`].
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Device {
    /// LSM303DLH
    Dlh,
    /// LSM303DLM
    Dlm,
    /// LSM303DLHC
    Dlhc,
    /// LSM303D
    D,
}

/// State of the chip's SA0 pin, which selects its I²C address.
///
/// Ignored on the DLHC, whose addresses are fixed.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum SA0 {
    /// SA0 tied to ground.
    Low,
    /// SA0 tied to supply.
    High,
}

/// Errors returned by the driver.
#[derive(Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Error<E> {
    /// Error from the underlying I²C bus.
    I2c(E),
    /// Detection found no LSM303 on the bus.
    DeviceNotFound,
}

/// A 3-axis reading (accelerometer or magnetometer), in raw sensor counts.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct Vector {
    /// X axis.
    pub x: i16,
    /// Y axis.
    pub y: i16,
    /// Z axis.
    pub z: i16,
}

/// I²C addresses and WHO_AM_I IDs used only for device detection.
mod detect {
    pub const D_SA0_HIGH: u8 = 0x1D; // 0b0011101
    pub const D_SA0_LOW: u8 = 0x1E; // 0b0011110
    pub const DLX_ACC_SA0_HIGH: u8 = 0x19; // 0b0011001
    pub const DLX_ACC_SA0_LOW: u8 = 0x18; // 0b0011000
    pub const DLX_MAG: u8 = 0x1E; // 0b0011110

    pub const WHO_ID_D: u8 = 0x49;
    pub const WHO_ID_DLM: u8 = 0x3C;
}
/// Marker type for the LSM303DLH, used as `Lsm303<I2C, Dlh>`.
pub struct Dlh;
/// Marker type for the LSM303DLM, used as `Lsm303<I2C, Dlm>`.
pub struct Dlm;
/// Marker type for the LSM303DLHC, used as `Lsm303<I2C, Dlhc>`.
pub struct Dlhc;
/// Marker type for the LSM303D, used as `Lsm303<I2C, D>`.
pub struct D;

/// Marker for the DLH/DLM/DLHC family, which share the magnetometer full-scale
/// (`GN`) table and register layout. Gates methods common to those three.
pub trait Dlx: Variant {}
impl Dlx for Dlh {}
impl Dlx for Dlm {}
impl Dlx for Dlhc {}

/// Per-variant hardware differences: I²C addresses, magnetometer output
/// layout, and the power-on default configuration. Implemented by the marker
/// types [`Dlh`], [`Dlm`], [`Dlhc`], and [`D`].
///
/// This replaces the Arduino library's runtime `translated_regs` table and
/// `_device` switches: each chip's quirks live in its trait impl and are
/// resolved at compile time.
// The returned futures are only awaited inside this crate / on a single-core
// embassy executor, so `Send` bounds are unnecessary. Same choice as
// `embedded-hal-async` makes for its own traits.
#[allow(async_fn_in_trait)]
#[maybe_async_cfg::maybe(sync(feature = "sync", keep_self), async(feature = "async", keep_self))]
pub trait Variant: Sized {
    /// The runtime [`Device`] this marker type corresponds to.
    ///
    /// Lets a runtime detection result be checked against the compile-time
    /// variant; see [`AnyLsm303::into_driver`].
    const DEVICE: Device;

    /// First register of a 6-byte magnetometer burst read, with the
    /// auto-increment bit already set where the chip requires it.
    const MAG_OUT_START: u8;

    /// Accelerometer I²C address for the given SA0 state.
    fn acc_address(sa0: SA0) -> u8;

    /// Magnetometer I²C address for the given SA0 state.
    fn mag_address(sa0: SA0) -> u8;

    /// Reassemble the 6 magnetometer bytes (in this chip's output order)
    /// into a signed X/Y/Z vector.
    fn parse_mag(buf: &[u8; 6]) -> Vector;

    /// Apply the power-on default configuration:
    /// enable both sensors at their datasheet-specified
    /// output data rates and full scales.
    async fn enable_default<I2C: I2c>(dev: &mut Lsm303<I2C, Self>)
    -> Result<(), Error<I2C::Error>>;
}
#[maybe_async_cfg::maybe(sync(feature = "sync", keep_self), async(feature = "async", keep_self))]
impl Variant for D {
    const DEVICE: Device = Device::D;

    // D returns X_L, X_H, Y_L, Y_H, Z_L, Z_H, and needs the auto-increment bit.
    const MAG_OUT_START: u8 = 0x08 | 0x80; // D_OUT_X_L_M | auto-increment

    fn acc_address(sa0: SA0) -> u8 {
        match sa0 {
            SA0::High => detect::D_SA0_HIGH,
            SA0::Low => detect::D_SA0_LOW,
        }
    }

    // On the D the accelerometer and magnetometer share one address.
    fn mag_address(sa0: SA0) -> u8 {
        Self::acc_address(sa0)
    }

    fn parse_mag(buf: &[u8; 6]) -> Vector {
        Vector {
            x: i16::from_le_bytes([buf[0], buf[1]]),
            y: i16::from_le_bytes([buf[2], buf[3]]),
            z: i16::from_le_bytes([buf[4], buf[5]]),
        }
    }

    async fn enable_default<I2C: I2c>(
        dev: &mut Lsm303<I2C, Self>,
    ) -> Result<(), Error<I2C::Error>> {
        // acc_address == mag_address on the D, so either accessor works.
        dev.write_mag_reg(reg_addr::CTRL2, 0x00).await?; // accel +/-2 g
        dev.write_mag_reg(reg_addr::CTRL1, 0x57).await?; // accel 50 Hz, all axes on
        dev.write_mag_reg(reg_addr::CTRL5, 0x64).await?; // mag high-res, 6.25 Hz
        dev.write_mag_reg(reg_addr::CTRL6, 0x20).await?; // mag +/-4 gauss
        dev.write_mag_reg(reg_addr::CTRL7, 0x00).await?; // mag continuous-conversion
        Ok(())
    }
}
#[maybe_async_cfg::maybe(sync(feature = "sync", keep_self), async(feature = "async", keep_self))]
impl Variant for Dlhc {
    const DEVICE: Device = Device::Dlhc;

    // DLHC returns X_H, X_L, Z_H, Z_L, Y_H, Y_L; its mag auto-increments on its own.
    const MAG_OUT_START: u8 = 0x03; // DLHC_OUT_X_H_M

    fn acc_address(_sa0: SA0) -> u8 {
        detect::DLX_ACC_SA0_HIGH // fixed; the DLHC has no configurable SA0
    }

    fn mag_address(_sa0: SA0) -> u8 {
        detect::DLX_MAG
    }

    fn parse_mag(buf: &[u8; 6]) -> Vector {
        Vector {
            x: i16::from_le_bytes([buf[1], buf[0]]),
            z: i16::from_le_bytes([buf[3], buf[2]]),
            y: i16::from_le_bytes([buf[5], buf[4]]),
        }
    }

    async fn enable_default<I2C: I2c>(
        dev: &mut Lsm303<I2C, Self>,
    ) -> Result<(), Error<I2C::Error>> {
        dev.write_acc_reg(reg_addr::CTRL_REG4_A, 0x08).await?; // +/-2 g, high-res
        dev.write_acc_reg(reg_addr::CTRL_REG1_A, 0x47).await?; // 50 Hz, all axes on
        dev.write_mag_reg(reg_addr::CRA_REG_M, 0x0C).await?; // 7.5 Hz
        dev.write_mag_reg(reg_addr::CRB_REG_M, 0x20).await?; // +/-1.3 gauss
        dev.write_mag_reg(reg_addr::MR_REG_M, 0x00).await?; // continuous-conversion
        Ok(())
    }
}
#[maybe_async_cfg::maybe(sync(feature = "sync", keep_self), async(feature = "async", keep_self))]
impl Variant for Dlm {
    const DEVICE: Device = Device::Dlm;

    // DLM returns X_H, X_L, Z_H, Z_L, Y_H, Y_L (same order as DLHC).
    const MAG_OUT_START: u8 = 0x03; // DLM_OUT_X_H_M

    fn acc_address(sa0: SA0) -> u8 {
        match sa0 {
            SA0::High => detect::DLX_ACC_SA0_HIGH,
            SA0::Low => detect::DLX_ACC_SA0_LOW,
        }
    }

    fn mag_address(_sa0: SA0) -> u8 {
        detect::DLX_MAG
    }

    fn parse_mag(buf: &[u8; 6]) -> Vector {
        Vector {
            x: i16::from_le_bytes([buf[1], buf[0]]),
            z: i16::from_le_bytes([buf[3], buf[2]]),
            y: i16::from_le_bytes([buf[5], buf[4]]),
        }
    }

    async fn enable_default<I2C: I2c>(
        dev: &mut Lsm303<I2C, Self>,
    ) -> Result<(), Error<I2C::Error>> {
        dev.write_acc_reg(reg_addr::CTRL_REG4_A, 0x00).await?; // +/-2 g
        dev.write_acc_reg(reg_addr::CTRL_REG1_A, 0x27).await?; // normal, 50 Hz, all axes
        dev.write_mag_reg(reg_addr::CRA_REG_M, 0x0C).await?;
        dev.write_mag_reg(reg_addr::CRB_REG_M, 0x20).await?;
        dev.write_mag_reg(reg_addr::MR_REG_M, 0x00).await?;
        Ok(())
    }
}
#[maybe_async_cfg::maybe(sync(feature = "sync", keep_self), async(feature = "async", keep_self))]
impl Variant for Dlh {
    const DEVICE: Device = Device::Dlh;

    // DLH returns X_H, X_L, Y_H, Y_L, Z_H, Z_L (Y before Z, unlike DLM/DLHC).
    const MAG_OUT_START: u8 = 0x03; // DLH_OUT_X_H_M

    fn acc_address(sa0: SA0) -> u8 {
        match sa0 {
            SA0::High => detect::DLX_ACC_SA0_HIGH,
            SA0::Low => detect::DLX_ACC_SA0_LOW,
        }
    }

    fn mag_address(_sa0: SA0) -> u8 {
        detect::DLX_MAG
    }

    fn parse_mag(buf: &[u8; 6]) -> Vector {
        Vector {
            x: i16::from_le_bytes([buf[1], buf[0]]),
            y: i16::from_le_bytes([buf[3], buf[2]]),
            z: i16::from_le_bytes([buf[5], buf[4]]),
        }
    }

    async fn enable_default<I2C: I2c>(
        dev: &mut Lsm303<I2C, Self>,
    ) -> Result<(), Error<I2C::Error>> {
        dev.write_acc_reg(reg_addr::CTRL_REG4_A, 0x00).await?;
        dev.write_acc_reg(reg_addr::CTRL_REG1_A, 0x27).await?;
        dev.write_mag_reg(reg_addr::CRA_REG_M, 0x0C).await?;
        dev.write_mag_reg(reg_addr::CRB_REG_M, 0x20).await?;
        dev.write_mag_reg(reg_addr::MR_REG_M, 0x00).await?;
        Ok(())
    }
}

/// Result of probing the bus: which chip was found and its SA0 state.
///
/// Get one from [`AnyLsm303::detect`], then turn it into a typed driver with
/// [`AnyLsm303::into_driver`].
pub struct AnyLsm303 {
    device: Device,
    sa0: SA0,
}

#[maybe_async_cfg::maybe(sync(feature = "sync", keep_self), async(feature = "async", keep_self))]
impl AnyLsm303 {
    /// Probe the bus for an LSM303.
    ///
    /// Pass `Some` for `device` and/or `sa0` to restrict the search; with both
    /// set, the bus is not probed at all.
    ///
    /// # DLHC vs DLM
    ///
    /// The DLHC and DLM cannot be told apart reliably. The DLHC answers the
    /// magnetometer `WHO_AM_I` with the DLM's ID (undocumented in its
    /// datasheet), and its accelerometer uses the same address as a DLM with
    /// SA0 high. Following Pololu's library, a chip with that ID is reported
    /// as a DLHC when found at the SA0-high address and as a DLM at SA0-low.
    /// A DLM with SA0 pulled high is therefore detected as a DLHC; pass
    /// `Some(Device::Dlm)` to avoid this.
    pub async fn detect<I2C: I2c>(
        i2c: &mut I2C,
        device: Option<Device>,
        sa0: Option<SA0>,
    ) -> Result<Self, Error<I2C::Error>> {
        Self::probe(i2c, device, sa0).await
    }

    /// Probe the bus to resolve the device type and SA0 state.
    ///
    /// Ported from Pololu's `LSM303::init` detection logic.
    async fn probe<I2C: I2c>(
        i2c: &mut I2C,
        device: Option<Device>,
        sa0: Option<SA0>,
    ) -> Result<Self, Error<I2C::Error>> {
        // Fully specified → trust the caller, don't probe.
        if let (Some(d), Some(s)) = (device, sa0) {
            return Ok(AnyLsm303 { device: d, sa0: s });
        }

        // LSM303D
        if device.is_none() || device == Some(Device::D) {
            if sa0 != Some(SA0::Low)
                && Self::test_reg(i2c, detect::D_SA0_HIGH, reg_addr::WHO_AM_I).await?
                    == Some(detect::WHO_ID_D)
            {
                return Ok(AnyLsm303 {
                    device: Device::D,
                    sa0: SA0::High,
                });
            }
            if sa0 != Some(SA0::High)
                && Self::test_reg(i2c, detect::D_SA0_LOW, reg_addr::WHO_AM_I).await?
                    == Some(detect::WHO_ID_D)
            {
                return Ok(AnyLsm303 {
                    device: Device::D,
                    sa0: SA0::Low,
                });
            }
        }

        // LSM303DLHC / DLM / DLH
        let is_dlx = matches!(
            device,
            None | Some(Device::Dlhc) | Some(Device::Dlm) | Some(Device::Dlh)
        );
        if is_dlx {
            if sa0 != Some(SA0::Low)
                && Self::test_reg(i2c, detect::DLX_ACC_SA0_HIGH, reg_addr::CTRL_REG1_A)
                    .await?
                    .is_some()
            {
                // Keep the caller's device if pinned; otherwise disambiguate by mag ID.
                // DLHC reports the DLM mag ID, so a match here means DLHC.
                let dev = match device {
                    Some(d) => d,
                    None if Self::mag_is_dlm(i2c).await? => Device::Dlhc,
                    None => Device::Dlh,
                };
                return Ok(AnyLsm303 {
                    device: dev,
                    sa0: SA0::High,
                });
            }
            if sa0 != Some(SA0::High)
                && Self::test_reg(i2c, detect::DLX_ACC_SA0_LOW, reg_addr::CTRL_REG1_A)
                    .await?
                    .is_some()
            {
                let dev = match device {
                    Some(d) => d,
                    None if Self::mag_is_dlm(i2c).await? => Device::Dlm,
                    None => Device::Dlh,
                };
                return Ok(AnyLsm303 {
                    device: dev,
                    sa0: SA0::Low,
                });
            }
        }

        Err(Error::DeviceNotFound)
    }

    /// True if the magnetometer reports the DLM WHO_AM_I ID.
    async fn mag_is_dlm<I2C: I2c>(i2c: &mut I2C) -> Result<bool, Error<I2C::Error>> {
        Ok(
            Self::test_reg(i2c, detect::DLX_MAG, reg_addr::WHO_AM_I_M).await?
                == Some(detect::WHO_ID_DLM),
        )
    }

    /// Read one register at `address`.
    ///
    /// `Ok(None)` means the device didn't ACK (i.e. nothing is at that
    /// address); real bus faults propagate as `Err`.
    async fn test_reg<I2C: I2c>(
        i2c: &mut I2C,
        address: u8,
        register: u8,
    ) -> Result<Option<u8>, Error<I2C::Error>> {
        let mut buf = [0u8];
        // i2c.write_read(0x1d, &[0x0f], &mut who).unwrap();
        // info!("WHO_AM_I = 0x{:02x} (expect 0x49 for LSM303D)", who[0]);

        match i2c.write_read(address, &[register], &mut buf).await {
            Ok(()) => Ok(Some(buf[0])),
            Err(e) => match e.kind() {
                ErrorKind::NoAcknowledge(_) => Ok(None),
                _ => Err(Error::I2c(e)),
            },
        }
    }
}

impl AnyLsm303 {
    /// The device type that was detected.
    pub fn device(&self) -> Device {
        self.device
    }

    /// The SA0 state that was detected.
    pub fn sa0(&self) -> SA0 {
        self.sa0
    }

    /// Turn a detection result into a typed driver, taking ownership of the bus.
    pub fn into_driver<I2C: I2c, V: Variant>(self, i2c: I2C) -> Result<Lsm303<I2C, V>, Device> {
        if self.device != V::DEVICE {
            return Err(self.device);
        }
        Ok(Lsm303::new_typed(i2c, self.sa0))
    }
}

/// Driver for one LSM303 chip on an I²C bus.
///
/// `V` is the chip variant ([`Dlh`], [`Dlm`], [`Dlhc`] or [`D`]); it selects
/// the addresses, register layout and which settings are available. Create one
/// with `Lsm303::<_, D>::new(i2c, sa0)` (or the matching variant), or from a
/// detection result with [`AnyLsm303::into_driver`].
pub struct Lsm303<I2C, V> {
    _variant: PhantomData<V>,
    i2c: I2C,
    sa0: SA0,
}

impl<I2C: I2c, V> Lsm303<I2C, V> {
    /// Wrap an already-identified device.
    ///
    /// Internal: used by [`AnyLsm303::detect`] and the per-variant
    /// constructors once the variant `V` is known.
    fn new_typed(i2c: I2C, sa0: SA0) -> Self {
        Self {
            _variant: PhantomData,
            i2c,
            sa0,
        }
    }

    /// Consume the driver and release the underlying I²C bus.
    pub fn release(self) -> I2C {
        self.i2c
    }
}

// Direct constructors that skip detection, use when you already know which
// chip is on the bus. Only the variant you name is monomorphized, so unused
// variants are stripped from the binary.
impl<I2C: I2c> Lsm303<I2C, Dlh> {
    /// Create a driver for an LSM303DLH at the given SA0 address.
    pub fn new(i2c: I2C, sa0: SA0) -> Self {
        Self::new_typed(i2c, sa0)
    }
}

impl<I2C: I2c> Lsm303<I2C, Dlm> {
    /// Create a driver for an LSM303DLM at the given SA0 address.
    pub fn new(i2c: I2C, sa0: SA0) -> Self {
        Self::new_typed(i2c, sa0)
    }
}

impl<I2C: I2c> Lsm303<I2C, Dlhc> {
    /// Create a driver for an LSM303DLHC at the given SA0 address.
    pub fn new(i2c: I2C, sa0: SA0) -> Self {
        Self::new_typed(i2c, sa0)
    }
}

impl<I2C: I2c> Lsm303<I2C, D> {
    /// Create a driver for an LSM303D at the given SA0 address.
    pub fn new(i2c: I2C, sa0: SA0) -> Self {
        Self::new_typed(i2c, sa0)
    }
}

// Operational methods, available once the variant `V` is known.
#[maybe_async_cfg::maybe(sync(feature = "sync", keep_self), async(feature = "async", keep_self))]
impl<I2C: I2c, V: Variant> Lsm303<I2C, V> {
    /// Write `value` to `reg` at the given I²C `address`.
    async fn write_register(
        &mut self,
        address: u8,
        reg: u8,
        value: u8,
    ) -> Result<(), Error<I2C::Error>> {
        self.i2c
            .write(address, &[reg, value])
            .await
            .map_err(Error::I2c)
    }

    /// Read one register at the given I²C `address`.
    async fn read_register(&mut self, address: u8, reg: u8) -> Result<u8, Error<I2C::Error>> {
        let mut buf = [0u8; 1];
        self.i2c
            .write_read(address, &[reg], &mut buf)
            .await
            .map_err(Error::I2c)?;
        Ok(buf[0])
    }

    /// Write to an accelerometer register.
    pub async fn write_acc_reg(&mut self, reg: u8, value: u8) -> Result<(), Error<I2C::Error>> {
        let address = V::acc_address(self.sa0);
        self.write_register(address, reg, value).await
    }

    /// Read an accelerometer register.
    pub async fn read_acc_reg(&mut self, reg: u8) -> Result<u8, Error<I2C::Error>> {
        let address = V::acc_address(self.sa0);
        self.read_register(address, reg).await
    }

    /// Write to a magnetometer register.
    pub async fn write_mag_reg(&mut self, reg: u8, value: u8) -> Result<(), Error<I2C::Error>> {
        let address = V::mag_address(self.sa0);
        self.write_register(address, reg, value).await
    }

    /// Read a magnetometer register.
    pub async fn read_mag_reg(&mut self, reg: u8) -> Result<u8, Error<I2C::Error>> {
        let address = V::mag_address(self.sa0);
        self.read_register(address, reg).await
    }

    /// Apply the power-on default configuration for this variant.
    pub async fn enable_default(&mut self) -> Result<(), Error<I2C::Error>> {
        V::enable_default(self).await
    }

    /// Read the three accelerometer axes.
    pub async fn read_accel(&mut self) -> Result<Vector, Error<I2C::Error>> {
        let address = V::acc_address(self.sa0);
        let mut buf = [0u8; 6];
        // The MSB of the sub-address enables auto-increment for the burst read.
        self.i2c
            .write_read(address, &[reg_addr::OUT_X_L_A | 0x80], &mut buf)
            .await
            .map_err(Error::I2c)?;
        // Accelerometer output is X_L, X_H, Y_L, Y_H, Z_L, Z_H on every variant.
        Ok(Vector {
            x: i16::from_le_bytes([buf[0], buf[1]]),
            y: i16::from_le_bytes([buf[2], buf[3]]),
            z: i16::from_le_bytes([buf[4], buf[5]]),
        })
    }

    /// Read the three magnetometer axes.
    pub async fn read_mag(&mut self) -> Result<Vector, Error<I2C::Error>> {
        let address = V::mag_address(self.sa0);
        let mut buf = [0u8; 6];
        self.i2c
            .write_read(address, &[V::MAG_OUT_START], &mut buf)
            .await
            .map_err(Error::I2c)?;
        Ok(V::parse_mag(&buf))
    }

    /// Read both the accelerometer and magnetometer.
    pub async fn read(&mut self) -> Result<(Vector, Vector), Error<I2C::Error>> {
        Ok((self.read_accel().await?, self.read_mag().await?))
    }

    /// Read-modify-write the `mask` bits of an accelerometer register, leaving
    /// the other bits untouched.
    async fn modify_acc_reg(
        &mut self,
        reg: u8,
        mask: u8,
        bits: u8,
    ) -> Result<(), Error<I2C::Error>> {
        let current = self.read_acc_reg(reg).await?;
        self.write_acc_reg(reg, (current & !mask) | (bits & mask))
            .await
    }

    /// Read-modify-write the `mask` bits of a magnetometer register.
    async fn modify_mag_reg(
        &mut self,
        reg: u8,
        mask: u8,
        bits: u8,
    ) -> Result<(), Error<I2C::Error>> {
        let current = self.read_mag_reg(reg).await?;
        self.write_mag_reg(reg, (current & !mask) | (bits & mask))
            .await
    }
}

// Accelerometer full-scale, gated per variant: each chip accepts only its own
// range set, and the D uses a different register/field than the DLx trio.
#[maybe_async_cfg::maybe(sync(feature = "sync", keep_self), async(feature = "async", keep_self))]
impl<I2C: I2c> Lsm303<I2C, Dlh> {
    /// Set the accelerometer full-scale range.
    pub async fn set_accel_scale(
        &mut self,
        scale: DlhDlmAccScale,
    ) -> Result<(), Error<I2C::Error>> {
        self.modify_acc_reg(reg_addr::CTRL_REG4_A, DlhDlmAccScale::MASK, scale.bits())
            .await
    }

    /// Set the accelerometer output data rate (also sets normal power mode).
    pub async fn set_accel_odr(&mut self, odr: DlhDlmAccOdr) -> Result<(), Error<I2C::Error>> {
        self.modify_acc_reg(reg_addr::CTRL_REG1_A, DlhDlmAccOdr::MASK, odr.bits())
            .await
    }

    /// Set the magnetometer output data rate (`DO` in `CRA_REG_M`).
    pub async fn set_mag_odr(&mut self, odr: DlhMagOdr) -> Result<(), Error<I2C::Error>> {
        self.modify_mag_reg(reg_addr::CRA_REG_M, DlhMagOdr::MASK, odr.bits())
            .await
    }

    /// Read back the currently configured accelerometer full-scale range.
    pub async fn read_accel_scale(&mut self) -> Result<DlhDlmAccScale, Error<I2C::Error>> {
        let reg = self.read_acc_reg(reg_addr::CTRL_REG4_A).await?;
        Ok(DlhDlmAccScale::from_reg(reg))
    }
}
#[maybe_async_cfg::maybe(sync(feature = "sync", keep_self), async(feature = "async", keep_self))]
impl<I2C: I2c> Lsm303<I2C, Dlm> {
    /// Set the accelerometer full-scale range.
    pub async fn set_accel_scale(
        &mut self,
        scale: DlhDlmAccScale,
    ) -> Result<(), Error<I2C::Error>> {
        self.modify_acc_reg(reg_addr::CTRL_REG4_A, DlhDlmAccScale::MASK, scale.bits())
            .await
    }

    /// Set the accelerometer output data rate (also sets normal power mode).
    pub async fn set_accel_odr(&mut self, odr: DlhDlmAccOdr) -> Result<(), Error<I2C::Error>> {
        self.modify_acc_reg(reg_addr::CTRL_REG1_A, DlhDlmAccOdr::MASK, odr.bits())
            .await
    }

    /// Set the magnetometer output data rate, including 220 Hz.
    pub async fn set_mag_odr(&mut self, odr: DlmDlhcMagOdr) -> Result<(), Error<I2C::Error>> {
        self.modify_mag_reg(reg_addr::CRA_REG_M, DlmDlhcMagOdr::MASK, odr.bits())
            .await
    }

    /// Read back the currently configured accelerometer full-scale range.
    pub async fn read_accel_scale(&mut self) -> Result<DlhDlmAccScale, Error<I2C::Error>> {
        let reg = self.read_acc_reg(reg_addr::CTRL_REG4_A).await?;
        Ok(DlhDlmAccScale::from_reg(reg))
    }
}
#[maybe_async_cfg::maybe(sync(feature = "sync", keep_self), async(feature = "async", keep_self))]
impl<I2C: I2c> Lsm303<I2C, Dlhc> {
    /// Set the accelerometer full-scale range.
    pub async fn set_accel_scale(&mut self, scale: DlhcAccScale) -> Result<(), Error<I2C::Error>> {
        self.modify_acc_reg(reg_addr::CTRL_REG4_A, DlhcAccScale::MASK, scale.bits())
            .await
    }

    /// Set the accelerometer output data rate.
    pub async fn set_accel_odr(&mut self, odr: DlhcAccOdr) -> Result<(), Error<I2C::Error>> {
        self.modify_acc_reg(reg_addr::CTRL_REG1_A, DlhcAccOdr::MASK, odr.bits())
            .await
    }

    /// Set the magnetometer output data rate, including 220 Hz.
    pub async fn set_mag_odr(&mut self, odr: DlmDlhcMagOdr) -> Result<(), Error<I2C::Error>> {
        self.modify_mag_reg(reg_addr::CRA_REG_M, DlmDlhcMagOdr::MASK, odr.bits())
            .await
    }

    /// Read back the currently configured accelerometer full-scale range.
    pub async fn read_accel_scale(&mut self) -> Result<DlhcAccScale, Error<I2C::Error>> {
        let reg = self.read_acc_reg(reg_addr::CTRL_REG4_A).await?;
        Ok(DlhcAccScale::from_reg(reg))
    }
}
#[maybe_async_cfg::maybe(sync(feature = "sync", keep_self), async(feature = "async", keep_self))]
impl<I2C: I2c> Lsm303<I2C, D> {
    /// Set the accelerometer full-scale range (`AFS` in `CTRL2`).
    pub async fn set_accel_scale(&mut self, scale: DAccScale) -> Result<(), Error<I2C::Error>> {
        self.modify_acc_reg(reg_addr::CTRL2, DAccScale::MASK, scale.bits())
            .await
    }

    /// Set the accelerometer output data rate (`AODR` in `CTRL1`).
    pub async fn set_accel_odr(&mut self, odr: DAccOdr) -> Result<(), Error<I2C::Error>> {
        self.modify_acc_reg(reg_addr::CTRL1, DAccOdr::MASK, odr.bits())
            .await
    }

    /// Set the magnetometer full-scale range (`MFS` in `CTRL6`).
    pub async fn set_mag_scale(&mut self, scale: DMagScale) -> Result<(), Error<I2C::Error>> {
        self.modify_mag_reg(reg_addr::CTRL6, DMagScale::MASK, scale.bits())
            .await
    }

    /// Set the magnetometer output data rate (`M_ODR` in `CTRL5`).
    pub async fn set_mag_odr(&mut self, odr: DMagOdr) -> Result<(), Error<I2C::Error>> {
        self.modify_mag_reg(reg_addr::CTRL5, DMagOdr::MASK, odr.bits())
            .await
    }

    /// Read back the currently configured accelerometer full-scale range.
    pub async fn read_accel_scale(&mut self) -> Result<DAccScale, Error<I2C::Error>> {
        let reg = self.read_acc_reg(reg_addr::CTRL2).await?;
        Ok(DAccScale::from_reg(reg))
    }
}

// Magnetometer full-scale, shared by the DLH/DLM/DLHC (identical `GN` table).
// Mag ODR is *not* shared: the DLM and DLHC support 220 Hz that the DLH lacks,
// so its setter lives on the per-variant blocks above.
#[maybe_async_cfg::maybe(sync(feature = "sync", keep_self), async(feature = "async", keep_self))]
impl<I2C: I2c, V: Dlx> Lsm303<I2C, V> {
    /// Set the magnetometer full-scale range.
    pub async fn set_mag_scale(&mut self, scale: DlxMagScale) -> Result<(), Error<I2C::Error>> {
        self.modify_mag_reg(reg_addr::CRB_REG_M, DlxMagScale::MASK, scale.bits())
            .await
    }
}
#[maybe_async_cfg::maybe(sync(feature = "sync", keep_self), async(feature = "async", keep_self))]
// The returned futures are only awaited inside this crate / on a single-core
// embassy executor, so `Send` bounds are unnecessary. Same choice as
// `embedded-hal-async` makes for its own traits.
#[allow(async_fn_in_trait)]
/// Chips with a built-in temperature sensor (currently only the LSM303D).
pub trait HasTemperature<I2C: I2c> {
    /// Read the raw temperature: a signed 12-bit value, 8 LSB/°C.
    ///
    /// The zero point is not calibrated, so this is only useful for relative
    /// changes. The sensor must be enabled first (`TEMP_EN` in `CTRL5`).
    async fn read_temperature(&mut self) -> Result<i16, Error<I2C::Error>>;
}
#[maybe_async_cfg::maybe(sync(feature = "sync", keep_self), async(feature = "async", keep_self))]
impl<I2C: I2c> HasTemperature<I2C> for Lsm303<I2C, D> {
    async fn read_temperature(&mut self) -> Result<i16, Error<I2C::Error>> {
        let temp_out_l = self.read_acc_reg(TEMP_OUT_L).await?;
        let temp_out_h = self.read_acc_reg(TEMP_OUT_H).await?;
        // 12-bit two's complement, right-justified: sign-extend from bit 11.
        let raw = i16::from_le_bytes([temp_out_l, temp_out_h]);
        Ok((raw << 4) >> 4)
    }
}