Skip to main content

edrv_adxl345/
lib.rs

1//! Driver for ADXL345.
2
3#![cfg_attr(not(test), no_std)]
4
5use embedded_hal_async::delay::DelayNs;
6
7pub mod blocking;
8
9/// Register map
10pub mod regs {
11    pub const DEVID: u8 = 0x00;
12    pub const THRESH_TAP: u8 = 0x1D;
13    pub const OFSX: u8 = 0x1E;
14    pub const OFSY: u8 = 0x1F;
15    pub const OFSZ: u8 = 0x20;
16    pub const DUR: u8 = 0x21;
17    pub const LATENT: u8 = 0x22;
18    pub const WINDOW: u8 = 0x23;
19    pub const THRESH_ACT: u8 = 0x24;
20    pub const THRESH_INACT: u8 = 0x25;
21    pub const TIME_INACT: u8 = 0x26;
22    pub const ACT_INACT_CTL: u8 = 0x27;
23    pub const THRESH_FF: u8 = 0x28;
24    pub const TIME_FF: u8 = 0x29;
25    pub const TAP_AXES: u8 = 0x2A;
26    pub const ACT_TAP_STATUS: u8 = 0x2B;
27    pub const BW_RATE: u8 = 0x2C;
28    pub const POWER_CTL: u8 = 0x2D;
29    pub const INT_ENABLE: u8 = 0x2E;
30    pub const INT_MAP: u8 = 0x2F;
31    pub const INT_SOURCE: u8 = 0x30;
32    pub const DATA_FORMAT: u8 = 0x31;
33    pub const DATAX0: u8 = 0x32;
34    pub const DATAX1: u8 = 0x33;
35    pub const DATAY0: u8 = 0x34;
36    pub const DATAY1: u8 = 0x35;
37    pub const DATAZ0: u8 = 0x36;
38    pub const DATAZ1: u8 = 0x37;
39    pub const FIFO_CTL: u8 = 0x38;
40    pub const FIFO_STATUS: u8 = 0x39;
41
42    /// `INT_SOURCE` bit 7: a new sample is available.
43    ///
44    /// Datasheet Rev. G, Register 0x30: "The DATA_READY bit is set when new data
45    /// is available and is cleared when no new data is available." The register
46    /// description adds that it is "always set if the corresponding events
47    /// occur, regardless of the INT_ENABLE register settings", so it can be
48    /// polled without routing the interrupt to a pin.
49    pub const INT_SOURCE_DATA_READY: u8 = 0x80;
50}
51
52/// `POWER_CTL` with the Measure bit (D3) set: measurement mode.
53pub const POWER_CTL_MEASURE: u8 = 0x08;
54
55/// `POWER_CTL` with every bit clear: standby mode.
56pub const POWER_CTL_STANDBY: u8 = 0x00;
57
58/// Extra polling budget added to the datasheet turn-on time before `init`
59/// gives up waiting for the first sample.
60pub(crate) const DATA_READY_POLL_MARGIN_MS: u32 = 20;
61
62pub const PRIMARY_ADDRESS: u8 = 0x53;
63pub const SECONDARY_ADDRESS: u8 = 0x1D;
64
65#[derive(Debug)]
66pub enum Error<IE> {
67    Bus(IE),
68    InvalidDevice,
69    /// The device did not report a new sample within the driver's polling
70    /// limit. `init` waits for the first sample, and returns this rather than
71    /// handing a caller data that was never measured.
72    Timeout,
73}
74
75impl<E> From<E> for Error<E> {
76    fn from(e: E) -> Self {
77        Error::Bus(e)
78    }
79}
80
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82#[repr(u8)]
83pub enum Range {
84    G2 = 0b00,
85    G4 = 0b01,
86    G8 = 0b10,
87    G16 = 0b11,
88}
89
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91#[repr(u8)]
92pub enum Rate {
93    Hz3200 = 0b1111,
94    Hz1600 = 0b1110,
95    Hz800 = 0b1101,
96    Hz400 = 0b1100,
97    Hz200 = 0b1011,
98    Hz100 = 0b1010,
99    Hz50 = 0b1001,
100    Hz25 = 0b1000,
101    Hz12_5 = 0b0111,
102    Hz6_25 = 0b0110,
103    Hz3_13 = 0b0101,
104    Hz1_56 = 0b0100,
105    Hz0_78 = 0b0011,
106    Hz0_39 = 0b0010,
107    Hz0_20 = 0b0001,
108    Hz0_10 = 0b0000,
109}
110
111impl Rate {
112    /// Nominal sample period in milliseconds, rounded up.
113    pub const fn period_ms(self) -> u32 {
114        match self {
115            Rate::Hz3200 => 1, // 0.3125 ms
116            Rate::Hz1600 => 1, // 0.625 ms
117            Rate::Hz800 => 2,  // 1.25 ms
118            Rate::Hz400 => 3,  // 2.5 ms
119            Rate::Hz200 => 5,  // 5 ms
120            Rate::Hz100 => 10, // 10 ms
121            Rate::Hz50 => 20,
122            Rate::Hz25 => 40,
123            Rate::Hz12_5 => 80,
124            Rate::Hz6_25 => 160,
125            Rate::Hz3_13 => 320,
126            Rate::Hz1_56 => 641,
127            Rate::Hz0_78 => 1282,
128            Rate::Hz0_39 => 2564,
129            Rate::Hz0_20 => 5000,
130            Rate::Hz0_10 => 10000,
131        }
132    }
133
134    /// Datasheet turn-on / wake-up time in milliseconds, rounded up.
135    ///
136    /// ADXL345 datasheet Rev. G, Table 1, note 7: "Turn-on and wake-up times are
137    /// determined by the user-defined bandwidth. At a 100 Hz data rate, the
138    /// turn-on and wake-up times are each approximately 11.1 ms. For other data
139    /// rates, the turn-on and wake-up times are each approximately
140    /// `1/(data rate) + 1.1` in milliseconds". The first sample after the
141    /// Measure bit is set is not available before this, so the data registers
142    /// still hold their reset value until then.
143    pub const fn turn_on_time_ms(self) -> u32 {
144        self.period_ms() + 2
145    }
146}
147
148/// Configuration settings for the ADXL345 accelerometer.
149///
150/// This struct holds the range and data rate settings for the accelerometer.
151/// The `range` field determines the measurement range of the accelerometer,
152/// and the `rate` field determines the data output rate.
153
154#[derive(Clone, Copy)]
155pub struct Config {
156    pub range: Range,
157    pub rate: Rate,
158}
159
160impl Default for Config {
161    fn default() -> Self {
162        Config {
163            range: Range::G2,
164            rate: Rate::Hz100,
165        }
166    }
167}
168/// A struct representing the ADXL345 accelerometer.
169//
170// This struct encapsulates the I2C interface, the device address, and the least significant bit (LSB) scale factor.
171// It provides methods to initialize the accelerometer, read raw acceleration data, and read acceleration values in g-force.
172pub struct ADXL345<I2C: embedded_hal_async::i2c::I2c> {
173    i2c: I2C,
174    addr: u8,
175    lsb_scale: f32,
176}
177
178impl<I2C: embedded_hal_async::i2c::I2c> ADXL345<I2C> {
179    pub fn new(i2c: I2C, addr: u8) -> Self {
180        Self {
181            i2c,
182            addr,
183            lsb_scale: 0.0,
184        }
185    }
186
187    /// Creates a new instance of the ADXL345 accelerometer with the primary address.
188    pub fn new_primary(i2c: I2C) -> Self {
189        Self::new(i2c, PRIMARY_ADDRESS)
190    }
191
192    pub fn new_secondary(i2c: I2C) -> Self {
193        Self::new(i2c, SECONDARY_ADDRESS)
194    }
195
196    /// Configure the part and wait until it has produced its first sample.
197    ///
198    /// The data registers hold their reset value (zero) from power-up until the
199    /// first conversion completes, which takes the datasheet's turn-on time
200    /// after the Measure bit is set (`1/data rate + 1.1` ms; about 11.1 ms at
201    /// the default 100 Hz). Returning from `init` before then makes a caller's
202    /// first read return `(0, 0, 0)` with no error.
203    ///
204    /// The configuration registers are therefore written while the part is
205    /// still in standby, and `init` only returns once `INT_SOURCE` reports
206    /// `DATA_READY` (or the turn-on budget expires with [`Error::Timeout`]).
207    /// Afterwards the part free-runs at the configured rate, so later reads
208    /// return the most recent sample without an additional wait.
209    pub async fn init(&mut self, config: Config, mut delay: impl DelayNs) -> Result<(), Error<I2C::Error>> {
210        let id = self.read_reg(regs::DEVID).await?;
211        if id != 0xE5 {
212            return Err(Error::InvalidDevice);
213        }
214
215        // The datasheet recommends clearing SLEEP/AUTO_SLEEP by passing through
216        // standby before re-entering measurement mode, and configuring the part
217        // while it is in standby.
218        self.write_reg(regs::POWER_CTL, POWER_CTL_STANDBY).await?; // Standby
219        self.write_reg(regs::POWER_CTL, 16).await?; // AUTO_SLEEP, cleared by the transition below
220
221        // Set data rate and range
222        let mut data_format = (config.range as u8) & 0x03;
223        data_format |= 0b100; // Set bit 2 to enable left justified mode
224        self.write_reg(regs::DATA_FORMAT, data_format).await?;
225
226        let bw_rate = (config.rate as u8) & 0x0F; // Set rate
227        self.write_reg(regs::BW_RATE, bw_rate).await?;
228
229        // Enter measurement mode last: the turn-on time is measured from this
230        // write, so the output data rate must already be programmed.
231        self.write_reg(regs::POWER_CTL, POWER_CTL_MEASURE).await?;
232
233        // Set scale factor based on the range
234        self.lsb_scale = match config.range {
235            Range::G2 => 4.0 / 65536.0,
236            Range::G4 => 8.0 / 65536.0,
237            Range::G8 => 16.0 / 65536.0,
238            Range::G16 => 32.0 / 65536.0,
239        };
240
241        self.wait_for_data_ready(config.rate, &mut delay).await?;
242
243        Ok(())
244    }
245
246    /// Wait until `INT_SOURCE.DATA_READY` is set, or give up after the
247    /// datasheet's turn-on time for the configured rate plus a small margin.
248    async fn wait_for_data_ready(&mut self, rate: Rate, delay: &mut impl DelayNs) -> Result<(), Error<I2C::Error>> {
249        let budget_ms = rate.turn_on_time_ms() + DATA_READY_POLL_MARGIN_MS;
250
251        for _ in 0..=budget_ms {
252            if self.read_reg(regs::INT_SOURCE).await? & regs::INT_SOURCE_DATA_READY != 0 {
253                return Ok(());
254            }
255            delay.delay_ms(1).await;
256        }
257
258        Err(Error::Timeout)
259    }
260
261    /// Reads the raw acceleration data from the sensor.
262    ///
263    /// This method reads the raw 16-bit acceleration values for the X, Y, and Z axes
264    /// from the sensor's data registers. The values are returned as a tuple of three
265    /// 16-bit integers representing the acceleration in each axis.
266    ///
267    /// # Returns
268    ///
269    /// A `Result` containing a tuple of three 16-bit integers `(x, y, z)` representing
270    /// the raw acceleration values for the X, Y, and Z axes, or an `Error` if the read
271    /// operation fails.
272    ///
273    /// # Errors
274    ///
275    /// Returns an `Error` if the I2C read operation fails.
276    pub async fn read_raw(&mut self) -> Result<(i16, i16, i16), Error<I2C::Error>> {
277        let mut buf = [0; 6];
278
279        self.i2c.write_read(self.addr, &[regs::DATAX0], &mut buf).await?;
280
281        let x = i16::from_le_bytes([buf[0], buf[1]]);
282        let y = i16::from_le_bytes([buf[2], buf[3]]);
283        let z = i16::from_le_bytes([buf[4], buf[5]]);
284
285        Ok((x, y, z))
286    }
287
288    /// Reads the acceleration values from the sensor and converts them to g-force.
289    /// The scaling factor is set during initialization based on the configured range.
290    ///
291    /// Returns a tuple of (x, y, z) acceleration values in g-force.
292    pub async fn read_accel(&mut self) -> Result<(f32, f32, f32), Error<I2C::Error>> {
293        let (x_raw, y_raw, z_raw) = self.read_raw().await?;
294
295        // Convert raw values to g-force
296        // The scaling factor is set during initialization based on the configured range
297        let x = x_raw as f32 * self.lsb_scale;
298        let y = y_raw as f32 * self.lsb_scale;
299        let z = z_raw as f32 * self.lsb_scale;
300
301        Ok((x, y, z))
302    }
303
304    pub async fn read_reg(&mut self, reg: u8) -> Result<u8, Error<I2C::Error>> {
305        let mut buf = [0];
306        self.i2c.write_read(self.addr, &[reg], &mut buf).await?;
307        Ok(buf[0])
308    }
309
310    // Add this new method to write to registers
311    pub async fn write_reg(&mut self, reg: u8, value: u8) -> Result<(), Error<I2C::Error>> {
312        self.i2c.write(self.addr, &[reg, value]).await?;
313        Ok(())
314    }
315}