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
use bitflags::bitflags;

use crate::register_address::{RegRead, StatusRegAuxA, WhoAmIA, WhoAmIM};

/// All possible errors in this crate
#[derive(Debug)]
pub enum Error<CommE> {
    /// I²C / SPI communication error
    Comm(CommE),
    /// Invalid input data provided
    InvalidInputData,
}

impl<CommE> From<CommE> for Error<CommE> {
    fn from(e: CommE) -> Self {
        Self::Comm(e)
    }
}

/// All possible errors in this crate
#[derive(Debug)]
pub struct ModeChangeError<CommE, DEV> {
    /// I²C / SPI communication error
    pub error: Error<CommE>,
    /// Original device without mode changed
    pub dev: DEV,
}

/// Device operation modes
pub mod mode {
    /// Marker type for magnetometer in one-shot (single) mode.
    #[derive(Debug)]
    pub enum MagOneShot {}
    /// Marker type for magnetometer in continuous mode.
    #[derive(Debug)]
    pub enum MagContinuous {}
}

/// An Accelerometer ID.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct AccelerometerId {
    raw: u8,
}

impl AccelerometerId {
    pub(crate) fn from_bits_truncate(raw: u8) -> Self {
        Self { raw }
    }

    /// Raw accelerometer ID.
    pub const fn raw(&self) -> u8 {
        self.raw
    }

    /// Check if the ID corresponds to the expected value.
    pub const fn is_correct(&self) -> bool {
        self.raw == WhoAmIA::ID
    }
}

/// An acceleration measurement.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Acceleration {
    pub(crate) x: u16,
    pub(crate) y: u16,
    pub(crate) z: u16,
    pub(crate) mode: AccelMode,
    pub(crate) scale: AccelScale,
}

impl RegRead<(u16, u16, u16)> for Acceleration {
    type Output = (u16, u16, u16);

    /// OUT_X_L_A
    const ADDR: u8 = 0x28;

    #[inline(always)]
    fn from_data(data: (u16, u16, u16)) -> Self::Output {
        data
    }
}

impl Acceleration {
    /// Raw acceleration in X-direction.
    #[inline]
    pub const fn x_raw(&self) -> u16 {
        self.x
    }

    /// Raw acceleration in Y-direction.
    #[inline]
    pub const fn y_raw(&self) -> u16 {
        self.y
    }

    /// Raw acceleration in Z-direction.
    #[inline]
    pub const fn z_raw(&self) -> u16 {
        self.z
    }

    /// Raw acceleration in X-, Y- and Z-directions.
    #[inline]
    pub const fn xyz_raw(&self) -> (u16, u16, u16) {
        (self.x, self.y, self.z)
    }

    /// Unscaled acceleration in X-direction.
    #[inline]
    pub const fn x_unscaled(&self) -> i16 {
        (self.x as i16) / self.mode.resolution_factor()
    }

    /// Unscaled acceleration in Y-direction.
    #[inline]
    pub const fn y_unscaled(&self) -> i16 {
        (self.y as i16) / self.mode.resolution_factor()
    }

    /// Unscaled acceleration in Z-direction.
    #[inline]
    pub const fn z_unscaled(&self) -> i16 {
        (self.z as i16) / self.mode.resolution_factor()
    }

    /// Unscaled acceleration in X-, Y- and Z-directions.
    #[inline]
    pub const fn xyz_unscaled(&self) -> (i16, i16, i16) {
        let resolution_factor = self.mode.resolution_factor();

        (
            (self.x as i16) / resolution_factor,
            (self.y as i16) / resolution_factor,
            (self.z as i16) / resolution_factor,
        )
    }

    /// Acceleration in X-direction in m*g* (milli-*g*).
    #[inline]
    pub const fn x_mg(&self) -> i32 {
        (self.x_unscaled() as i32) * self.mode.scaling_factor(self.scale)
    }

    /// Acceleration in Y-direction in m*g* (milli-*g*).
    #[inline]
    pub const fn y_mg(&self) -> i32 {
        (self.y_unscaled() as i32) * self.mode.scaling_factor(self.scale)
    }

    /// Acceleration in Z-direction in m*g* (milli-*g*).
    #[inline]
    pub const fn z_mg(&self) -> i32 {
        (self.z_unscaled() as i32) * self.mode.scaling_factor(self.scale)
    }

    /// Acceleration in X-, Y- and Z-directions in m*g* (milli-*g*).
    #[inline]
    pub const fn xyz_mg(&self) -> (i32, i32, i32) {
        let (x_unscaled, y_unscaled, z_unscaled) = self.xyz_unscaled();
        let scaling_factor = self.mode.scaling_factor(self.scale);

        (
            (x_unscaled as i32) * scaling_factor,
            (y_unscaled as i32) * scaling_factor,
            (z_unscaled as i32) * scaling_factor,
        )
    }
}

/// A Magnetometer ID.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MagnetometerId {
    raw: u8,
}

impl MagnetometerId {
    pub(crate) fn from_bits_truncate(raw: u8) -> Self {
        Self { raw }
    }

    /// Raw magnetometer ID.
    pub const fn raw(&self) -> u8 {
        self.raw
    }

    /// Check if the ID corresponds to the expected value.
    pub const fn is_correct(&self) -> bool {
        self.raw == WhoAmIM::ID
    }
}

/// A magnetic field measurement.
#[derive(Debug, Default, Clone, Copy, PartialEq)]
pub struct MagneticField {
    pub(crate) x: u16,
    pub(crate) y: u16,
    pub(crate) z: u16,
}

impl RegRead<(u16, u16, u16)> for MagneticField {
    type Output = Self;

    /// OUTX_L_REG_M
    const ADDR: u8 = 0x68;

    #[inline(always)]
    fn from_data((x, y, z): (u16, u16, u16)) -> Self::Output {
        Self { x, y, z }
    }
}

impl MagneticField {
    const SCALING_FACTOR: i32 = 150;

    /// Raw magnetic field in X-direction.
    #[inline]
    pub const fn x_raw(&self) -> u16 {
        self.x
    }

    /// Raw magnetic field in Y-direction.
    #[inline]
    pub const fn y_raw(&self) -> u16 {
        self.y
    }

    /// Raw magnetic field in Z-direction.
    #[inline]
    pub const fn z_raw(&self) -> u16 {
        self.z
    }

    /// Raw magnetic field in X-, Y- and Z-directions.
    #[inline]
    pub const fn xyz_raw(&self) -> (u16, u16, u16) {
        (self.x, self.y, self.z)
    }

    /// Unscaled magnetic field in X-direction.
    #[inline]
    pub const fn x_unscaled(&self) -> i16 {
        self.x as i16
    }

    /// Unscaled magnetic field in Y-direction.
    #[inline]
    pub const fn y_unscaled(&self) -> i16 {
        self.y as i16
    }

    /// Unscaled magnetic field in Z-direction.
    #[inline]
    pub const fn z_unscaled(&self) -> i16 {
        self.z as i16
    }

    /// Unscaled magnetic field in X-, Y- and Z-directions.
    #[inline]
    pub const fn xyz_unscaled(&self) -> (i16, i16, i16) {
        (self.x as i16, self.y as i16, self.z as i16)
    }

    /// Magnetic field in X-direction in nT (nano-Tesla).
    #[inline]
    pub const fn x_nt(&self) -> i32 {
        (self.x_unscaled() as i32) * Self::SCALING_FACTOR
    }

    /// Magnetic field in Y-direction in nT (nano-Tesla).
    #[inline]
    pub const fn y_nt(&self) -> i32 {
        (self.y_unscaled() as i32) * Self::SCALING_FACTOR
    }

    /// Magnetic field in Z-direction in nT (nano-Tesla).
    #[inline]
    pub const fn z_nt(&self) -> i32 {
        (self.z_unscaled() as i32) * Self::SCALING_FACTOR
    }

    /// Magnetic field in X-, Y- and Z-directions in nT (nano-Tesla).
    #[inline]
    pub const fn xyz_nt(&self) -> (i32, i32, i32) {
        (self.x_nt(), self.y_nt(), self.z_nt())
    }
}

/// Accelerometer output data rate
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum AccelOutputDataRate {
    /// 1 Hz (all modes)
    Hz1,
    /// 10 Hz all modes)
    Hz10,
    /// 25 Hz (all modes)
    Hz25,
    /// 50 Hz (all modes)
    Hz50,
    /// 100 Hz (all modes)
    Hz100,
    /// 200 Hz (all modes)
    Hz200,
    /// 400 Hz (all modes)
    Hz400,
    /// 1.344 kHz (only normal and high-resolution modes)
    Khz1_344,
    /// 1.620 kHz (only low-power mode)
    Khz1_620LowPower,
    /// 5.376 kHz (only low-power mode)
    Khz5_376LowPower,
}

impl AccelOutputDataRate {
    /// Create an `AccelOutputDataRate` with the given frequency in Hertz.
    pub const fn from_hertz(hz: u16) -> Option<Self> {
        Some(match hz {
            1 => Self::Hz1,
            10 => Self::Hz10,
            25 => Self::Hz25,
            50 => Self::Hz50,
            100 => Self::Hz100,
            200 => Self::Hz200,
            400 => Self::Hz400,
            1344 => Self::Khz1_344,
            1620 => Self::Khz1_620LowPower,
            5376 => Self::Khz5_376LowPower,
            _ => return None,
        })
    }

    /// 1/ODR ms
    pub(crate) const fn turn_on_time_us_frac_1(&self) -> u32 {
        match self {
            Self::Hz1 => 1000,
            Self::Hz10 => 100,
            Self::Hz25 => 40,
            Self::Hz50 => 20,
            Self::Hz100 => 10,
            Self::Hz200 => 5,
            Self::Hz400 => 3,            //  2.5
            Self::Khz1_344 => 1,         // ~0.7
            Self::Khz1_620LowPower => 1, // ~0.6
            Self::Khz5_376LowPower => 1, // ~0.2
        }
    }

    /// 7/ODR ms
    pub(crate) const fn turn_on_time_us_frac_7(&self) -> u32 {
        match self {
            Self::Hz1 => 7000,
            Self::Hz10 => 700,
            Self::Hz25 => 280,
            Self::Hz50 => 140,
            Self::Hz100 => 70,
            Self::Hz200 => 35,
            Self::Hz400 => 18,           // 17.5
            Self::Khz1_344 => 6,         // ~5.2
            Self::Khz1_620LowPower => 5, // ~4.3
            Self::Khz5_376LowPower => 2, // ~1.3
        }
    }
}

/// Accelerometer mode
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum AccelMode {
    /// Power down
    PowerDown,
    /// Low power (8-bit)
    LowPower,
    /// Normal mode (10-bit)
    Normal,
    /// High resolution (12-bit)
    HighResolution,
}

impl AccelMode {
    pub(crate) const fn turn_on_time_us(&self, odr: AccelOutputDataRate) -> u32 {
        match self {
            Self::PowerDown => 0,
            Self::LowPower => 1000,
            Self::Normal => 1600,
            Self::HighResolution => odr.turn_on_time_us_frac_7(),
        }
    }

    pub(crate) const fn change_time_us(&self, other: AccelMode, odr: AccelOutputDataRate) -> u32 {
        match (self, other) {
            (Self::HighResolution, Self::LowPower) => odr.turn_on_time_us_frac_1(),
            (Self::HighResolution, Self::Normal) => odr.turn_on_time_us_frac_1(),
            (Self::Normal, Self::LowPower) => odr.turn_on_time_us_frac_1(),
            (Self::Normal, Self::HighResolution) => odr.turn_on_time_us_frac_7(),
            (Self::LowPower, Self::Normal) => odr.turn_on_time_us_frac_1(),
            (Self::LowPower, Self::HighResolution) => odr.turn_on_time_us_frac_7(),
            (Self::PowerDown, new_mode) => new_mode.turn_on_time_us(odr),
            _ => 0,
        }
    }

    pub(crate) const fn resolution_factor(&self) -> i16 {
        match self {
            Self::PowerDown => 1,
            Self::HighResolution => 1 << 4,
            Self::Normal => 1 << 6,
            Self::LowPower => 1 << 8,
        }
    }

    pub(crate) const fn scaling_factor(&self, scale: AccelScale) -> i32 {
        match self {
            Self::PowerDown => 0,
            Self::HighResolution => scale as i32 / 2,
            Self::Normal => scale as i32 * 2,
            Self::LowPower => scale as i32 * 8,
        }
    }
}

/// Accelerometer scaling factor
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum AccelScale {
    /// Plus or minus 2g
    G2 = 2,
    /// Plus or minus 4g
    G4 = 4,
    /// Plus or minus 8g
    G8 = 8,
    /// Plus or minus 16g
    G16 = 16,
}

/// Magnetometer output data rate
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum MagOutputDataRate {
    /// 10 Hz
    Hz10,
    /// 20 Hz
    Hz20,
    /// 50 Hz
    Hz50,
    /// 100 Hz
    Hz100,
}

impl MagOutputDataRate {
    /// Create an `MagOutputDataRate` with the given frequency in Hertz.
    pub const fn from_hertz(hz: u16) -> Option<Self> {
        Some(match hz {
            10 => Self::Hz10,
            20 => Self::Hz20,
            50 => Self::Hz50,
            100 => Self::Hz100,
            _ => return None,
        })
    }

    /// 1/ODR ms
    pub(crate) const fn turn_on_time_us_frac_1(&self) -> u32 {
        match self {
            Self::Hz10 => 100,
            Self::Hz20 => 50,
            Self::Hz50 => 20,
            Self::Hz100 => 10,
        }
    }
}

/// Magnetometer mode
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum MagMode {
    /// Low-power mode
    LowPower,
    /// High resolution mode
    HighResolution,
}

impl Default for MagMode {
    fn default() -> Self {
        Self::HighResolution
    }
}

impl MagMode {
    pub(crate) const fn turn_on_time_us(&self) -> u32 {
        match self {
            Self::LowPower => 9400,
            Self::HighResolution => 6400,
        }
    }
}

bitflags! {
    #[derive(Debug, Default, Copy, Clone, PartialEq)]
    pub struct StatusFlags: u8 {
        const ZYXOR = 0b10000000;
        const ZOR   = 0b01000000;
        const YOR   = 0b00100000;
        const XOR   = 0b00010000;
        const ZYXDA = 0b00001000;
        const ZDA   = 0b00000100;
        const YDA   = 0b00000010;
        const XDA   = 0b00000001;
    }
}

/// Data status
#[derive(Debug, Default, Clone, Copy, PartialEq)]
pub struct Status {
    flags: StatusFlags,
}

impl Status {
    pub(crate) const fn new(flags: StatusFlags) -> Self {
        Self { flags }
    }

    /// X-axis new data available.
    #[inline]
    pub const fn x_new_data(&self) -> bool {
        self.flags.contains(StatusFlags::XDA)
    }

    /// Y-axis new data available.
    #[inline]
    pub const fn y_new_data(&self) -> bool {
        self.flags.contains(StatusFlags::YDA)
    }

    /// Z-axis new data available.
    #[inline]
    pub const fn z_new_data(&self) -> bool {
        self.flags.contains(StatusFlags::ZDA)
    }

    /// X-, Y- and Z-axis new data available.
    #[inline]
    pub const fn xyz_new_data(&self) -> bool {
        self.flags.contains(StatusFlags::ZYXDA)
    }

    /// X-axis data overrun.
    #[inline]
    pub const fn x_overrun(&self) -> bool {
        self.flags.contains(StatusFlags::XOR)
    }

    /// Y-axis data overrun.
    #[inline]
    pub const fn y_overrun(&self) -> bool {
        self.flags.contains(StatusFlags::YOR)
    }

    /// Z-axis data overrun.
    #[inline]
    pub const fn z_overrun(&self) -> bool {
        self.flags.contains(StatusFlags::ZOR)
    }

    /// X-, Y- and Z-axis data overrun.
    #[inline]
    pub const fn xyz_overrun(&self) -> bool {
        self.flags.contains(StatusFlags::ZYXOR)
    }
}

/// Temperature sensor status
#[derive(Debug, Default, Clone, Copy, PartialEq)]
pub struct TemperatureStatus {
    flags: StatusRegAuxA,
}

impl TemperatureStatus {
    pub(crate) const fn new(flags: StatusRegAuxA) -> Self {
        Self { flags }
    }

    /// Temperature data overrun.
    #[inline]
    pub const fn overrun(&self) -> bool {
        self.flags.contains(StatusRegAuxA::TOR)
    }

    /// Temperature new data available.
    #[inline]
    pub const fn new_data(&self) -> bool {
        self.flags.contains(StatusRegAuxA::TDA)
    }
}

/// A temperature measurement.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Temperature {
    pub(crate) raw: u16,
}

impl RegRead<u16> for Temperature {
    type Output = Self;

    /// OUT_TEMP_L_A
    const ADDR: u8 = 0x0C;

    #[inline]
    fn from_data(data: u16) -> Self::Output {
        Temperature { raw: data }
    }
}

impl Temperature {
    const DEFAULT: f32 = 25.0;

    /// Raw temperature.
    #[inline]
    pub const fn raw(&self) -> u16 {
        self.raw
    }

    /// Unscaled temperature.
    #[inline]
    pub const fn unscaled(&self) -> i16 {
        self.raw as i16
    }

    /// Temperature in °C.
    #[inline]
    pub fn degrees_celsius(&self) -> f32 {
        (self.unscaled() as f32) / 256.0 + Self::DEFAULT
    }
}

/// A FIFO mode.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum FifoMode {
    /// Bypass mode
    Bypass,
    /// FIFO mode
    Fifo,
    /// Stream mode
    Stream,
    /// Stream-to-FIFO mode
    StreamToFifo,
}

/// An interrupt.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Interrupt {
    /// AOI1 interrupt on INT1 pin.
    Aoi1,
    /// AOI2 interrupt on INT1 pin.
    Aoi2,
    /// CLICK interrupt on INT1 pin.
    Click,
    /// DRDY1 interrupt on INT1 pin.
    DataReady1,
    /// DRDY2 interrupt on INT1 pin.
    DataReady2,
    /// FIFO overrun interrupt on INT1 pin.
    FifoOverrun,
    /// FIFO watermark interrupt on INT1 pin.
    FifoWatermark,
}