use crate::registers::{AccelRange, GyroRange, Status1, TapStatusReg};
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct RawSample {
pub accel: [i16; 3],
pub gyro: [i16; 3],
pub temperature_raw: i16,
pub timestamp: u32,
}
const fn i16_at(b: &[u8; 17], offset: usize) -> i16 {
i16::from_le_bytes([b[offset], b[offset + 1]])
}
impl RawSample {
pub(crate) const fn from_block(b: &[u8; 17]) -> Self {
Self {
timestamp: (b[0] as u32) | ((b[1] as u32) << 8) | ((b[2] as u32) << 16),
temperature_raw: i16_at(b, 3),
accel: [i16_at(b, 5), i16_at(b, 7), i16_at(b, 9)],
gyro: [i16_at(b, 11), i16_at(b, 13), i16_at(b, 15)],
}
}
}
#[derive(Clone, Copy, PartialEq, Debug, Default)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct Sample {
pub accel_g: [f32; 3],
pub gyro_dps: [f32; 3],
pub temperature_c: f32,
pub timestamp: u32,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct Scales {
pub accel: AccelRange,
pub gyro: GyroRange,
}
impl Default for Scales {
fn default() -> Self {
Self {
accel: AccelRange::G4,
gyro: GyroRange::Dps512,
}
}
}
impl Scales {
#[must_use]
pub fn convert(&self, raw: &RawSample) -> Sample {
let a = f32::from(self.accel.lsb_per_g());
let g = f32::from(self.gyro.lsb_per_dps());
Sample {
accel_g: [
f32::from(raw.accel[0]) / a,
f32::from(raw.accel[1]) / a,
f32::from(raw.accel[2]) / a,
],
gyro_dps: [
f32::from(raw.gyro[0]) / g,
f32::from(raw.gyro[1]) / g,
f32::from(raw.gyro[2]) / g,
],
temperature_c: temperature_c(raw.temperature_raw),
timestamp: raw.timestamp,
}
}
#[must_use]
pub fn accel_mg(&self, raw: [i16; 3]) -> [i32; 3] {
let lsb = i32::from(self.accel.lsb_per_g());
[
i32::from(raw[0]) * 1000 / lsb,
i32::from(raw[1]) * 1000 / lsb,
i32::from(raw[2]) * 1000 / lsb,
]
}
#[must_use]
pub fn gyro_mdps(&self, raw: [i16; 3]) -> [i32; 3] {
let lsb = i32::from(self.gyro.lsb_per_dps());
[
i32::from(raw[0]) * 1000 / lsb,
i32::from(raw[1]) * 1000 / lsb,
i32::from(raw[2]) * 1000 / lsb,
]
}
}
#[must_use]
pub fn temperature_c(raw: i16) -> f32 {
f32::from(raw) / 256.0
}
#[must_use]
pub fn temperature_mdegc(raw: i16) -> i32 {
i32::from(raw) * 1000 / 256
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct DataStatus {
pub accel_ready: bool,
pub gyro_ready: bool,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct ActivityStatus {
pub significant_motion: bool,
pub no_motion: bool,
pub any_motion: bool,
pub pedometer_event: bool,
pub wake_on_motion: bool,
pub tap: bool,
}
impl ActivityStatus {
pub(crate) const fn from_status1(s: Status1) -> Self {
Self {
significant_motion: s.significant_motion,
no_motion: s.no_motion,
any_motion: s.any_motion,
pedometer_event: s.pedometer,
wake_on_motion: s.wake_on_motion,
tap: s.tap,
}
}
#[must_use]
pub const fn any(&self) -> bool {
self.significant_motion
|| self.no_motion
|| self.any_motion
|| self.pedometer_event
|| self.wake_on_motion
|| self.tap
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Axis {
X,
Y,
Z,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum TapCount {
Single,
Double,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct TapEvent {
pub count: TapCount,
pub axis: Axis,
pub negative_polarity: bool,
}
impl TapEvent {
pub(crate) const fn from_reg(reg: TapStatusReg) -> Option<Self> {
let count = match reg.count_bits {
1 => TapCount::Single,
2 => TapCount::Double,
_ => return None,
};
let axis = match reg.axis_bits {
1 => Axis::X,
2 => Axis::Y,
3 => Axis::Z,
_ => return None,
};
Some(Self {
count,
axis,
negative_polarity: reg.negative_polarity,
})
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct FifoStatus {
pub full: bool,
pub watermark_reached: bool,
pub overflow: bool,
pub not_empty: bool,
pub bytes_available: u16,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum FifoFrameFormat {
AccelOnly,
GyroOnly,
AccelAndGyro,
}
impl FifoFrameFormat {
#[must_use]
pub const fn frame_len(self) -> usize {
match self {
Self::AccelOnly | Self::GyroOnly => 6,
Self::AccelAndGyro => 12,
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct FifoFrame {
pub accel: Option<[i16; 3]>,
pub gyro: Option<[i16; 3]>,
}
const fn axes_at(b: &[u8], offset: usize) -> [i16; 3] {
[
i16::from_le_bytes([b[offset], b[offset + 1]]),
i16::from_le_bytes([b[offset + 2], b[offset + 3]]),
i16::from_le_bytes([b[offset + 4], b[offset + 5]]),
]
}
#[derive(Clone, Debug)]
pub struct FifoFrames<'a> {
bytes: &'a [u8],
format: FifoFrameFormat,
offset: usize,
}
impl<'a> FifoFrames<'a> {
#[must_use]
pub const fn new(bytes: &'a [u8], format: FifoFrameFormat) -> Self {
Self {
bytes,
format,
offset: 0,
}
}
}
impl Iterator for FifoFrames<'_> {
type Item = FifoFrame;
fn next(&mut self) -> Option<Self::Item> {
let len = self.format.frame_len();
let frame = self.bytes.get(self.offset..self.offset + len)?;
self.offset += len;
Some(match self.format {
FifoFrameFormat::AccelOnly => FifoFrame {
accel: Some(axes_at(frame, 0)),
gyro: None,
},
FifoFrameFormat::GyroOnly => FifoFrame {
accel: None,
gyro: Some(axes_at(frame, 0)),
},
FifoFrameFormat::AccelAndGyro => FifoFrame {
accel: Some(axes_at(frame, 0)),
gyro: Some(axes_at(frame, 6)),
},
})
}
}
#[derive(Clone, Copy, PartialEq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct SelfTestReport {
pub delta: [f32; 3],
pub passed: bool,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct GyroGains(pub [u8; 6]);
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct DeviceId {
pub who_am_i: u8,
pub revision: u8,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct UniqueId {
pub firmware: [u8; 3],
pub usid: [u8; 6],
}
#[must_use]
#[allow(clippy::cast_possible_truncation)]
pub fn accel_offset_to_q4_12(g: f32) -> Option<i16> {
if !(-8.0..8.0).contains(&g) {
return None;
}
let scaled = g * 4096.0;
let rounded = if scaled >= 0.0 {
scaled + 0.5
} else {
scaled - 0.5
};
Some(rounded as i32 as i16)
}
#[must_use]
#[allow(clippy::cast_possible_truncation)]
pub fn gyro_offset_to_q11_5(dps: f32) -> Option<i16> {
if !(-1024.0..1024.0).contains(&dps) {
return None;
}
let scaled = dps * 32.0;
let rounded = if scaled >= 0.0 {
scaled + 0.5
} else {
scaled - 0.5
};
Some(rounded as i32 as i16)
}
#[must_use]
pub fn selftest_accel_delta_mg(raw: i16) -> f32 {
f32::from(raw) * 0.5
}
#[must_use]
pub fn selftest_gyro_delta_dps(raw: i16) -> f32 {
f32::from(raw) * 0.0625
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn block_decode() {
let mut b = [0u8; 17];
b[0..3].copy_from_slice(&[0x56, 0x34, 0x12]);
b[3..5].copy_from_slice(&0x1980i16.to_le_bytes()); b[9..11].copy_from_slice(&8192i16.to_le_bytes()); b[11..13].copy_from_slice(&(-64i16).to_le_bytes()); let raw = RawSample::from_block(&b);
assert_eq!(raw.timestamp, 0x12_3456);
assert_eq!(raw.accel, [0, 0, 8192]);
assert_eq!(raw.gyro, [-64, 0, 0]);
let sample = Scales::default().convert(&raw);
assert!((sample.accel_g[2] - 1.0).abs() < 1e-6);
assert!((sample.gyro_dps[0] + 1.0).abs() < 1e-6);
assert!((sample.temperature_c - 25.5).abs() < 1e-6);
}
#[test]
fn scale_extremes() {
let scales = Scales {
accel: AccelRange::G16,
gyro: GyroRange::Dps2048,
};
let raw = RawSample {
accel: [-32768, 16384, 0],
gyro: [-32768, 16384, 0],
temperature_raw: 0,
timestamp: 0,
};
let s = scales.convert(&raw);
assert!((s.accel_g[0] + 16.0).abs() < 1e-6);
assert!((s.accel_g[1] - 8.0).abs() < 1e-6);
assert!((s.gyro_dps[0] + 2048.0).abs() < 1e-3);
assert_eq!(scales.accel_mg(raw.accel), [-16000, 8000, 0]);
assert_eq!(scales.gyro_mdps(raw.gyro), [-2_048_000, 1_024_000, 0]);
}
#[test]
fn temperature_forms() {
assert_eq!(temperature_mdegc(0x1980), 25500);
assert_eq!(temperature_mdegc(-256), -1000);
assert!((temperature_c(0x1980) - 25.5).abs() < 1e-6);
}
#[test]
fn offset_fixed_point() {
assert_eq!(accel_offset_to_q4_12(1.0), Some(4096));
assert_eq!(accel_offset_to_q4_12(-0.5), Some(-2048));
assert_eq!(accel_offset_to_q4_12(8.0), None);
assert_eq!(accel_offset_to_q4_12(-8.0), Some(-32768));
assert_eq!(accel_offset_to_q4_12(f32::NAN), None);
assert!(accel_offset_to_q4_12(7.999).is_some());
assert_eq!(gyro_offset_to_q11_5(100.0), Some(3200));
assert_eq!(gyro_offset_to_q11_5(-1024.0), Some(-32768));
assert_eq!(gyro_offset_to_q11_5(1024.0), None);
assert_eq!(gyro_offset_to_q11_5(f32::INFINITY), None);
}
#[test]
fn selftest_units() {
assert!((selftest_accel_delta_mg(400) - 200.0).abs() < 1e-6);
assert!((selftest_gyro_delta_dps(4800) - 300.0).abs() < 1e-6);
}
#[test]
fn fifo_frames_both_sensors() {
let mut buf = [0u8; 25]; buf[0..2].copy_from_slice(&100i16.to_le_bytes());
buf[6..8].copy_from_slice(&(-200i16).to_le_bytes());
buf[12..14].copy_from_slice(&300i16.to_le_bytes());
let frames: Vec<_> = FifoFrames::new(&buf, FifoFrameFormat::AccelAndGyro).collect();
assert_eq!(frames.len(), 2);
assert_eq!(frames[0].accel, Some([100, 0, 0]));
assert_eq!(frames[0].gyro, Some([-200, 0, 0]));
assert_eq!(frames[1].accel, Some([300, 0, 0]));
}
#[test]
fn fifo_frames_single_sensor() {
let mut buf = [0u8; 12];
buf[4..6].copy_from_slice(&8192i16.to_le_bytes());
let frames: Vec<_> = FifoFrames::new(&buf, FifoFrameFormat::AccelOnly).collect();
assert_eq!(frames.len(), 2);
assert_eq!(frames[0].accel, Some([0, 0, 8192]));
assert_eq!(frames[0].gyro, None);
let gyro_frames: Vec<_> = FifoFrames::new(&buf, FifoFrameFormat::GyroOnly).collect();
assert_eq!(gyro_frames[0].accel, None);
assert_eq!(gyro_frames[0].gyro, Some([0, 0, 8192]));
}
#[test]
fn tap_decode() {
let ev = TapEvent::from_reg(TapStatusReg::from_bits(0xB2)).unwrap();
assert_eq!(ev.count, TapCount::Double);
assert_eq!(ev.axis, Axis::Z);
assert!(ev.negative_polarity);
assert!(TapEvent::from_reg(TapStatusReg::from_bits(0x00)).is_none());
assert!(TapEvent::from_reg(TapStatusReg::from_bits(0x13)).is_none());
assert!(TapEvent::from_reg(TapStatusReg::from_bits(0x01)).is_none());
}
}