Skip to main content

r_d_inclita_sofware/sensors/
adxl345.rs

1use crate::telemetry::data::{AccelData, DATA_CHANNEL, LATEST_TELEMETRY, LogEvent};
2use defmt::{error, info};
3use embassy_stm32::i2c::I2c;
4use embassy_stm32::mode::Blocking;
5use embassy_time::{Duration, Ticker};
6use lh_adxl345 as adxl; // Brings in the .accel_raw() method
7
8#[embassy_executor::task]
9pub async fn adxl343_task(i2c: I2c<'static, Blocking, embassy_stm32::i2c::Master>) {
10    info!("Initializing ADXL345 via lh-adxl345 crate at 0x1D...");
11
12    // 1. Wrap the Embassy I2C bus in the crate's I2C struct
13    // This is where we solve the SDO pull-up address issue!
14    let adxl_bus = adxl::AdxlBusI2c {
15        i2c,
16        addr: 0x1D, // Your custom address because SDO is pulled HIGH
17    };
18
19    // 2. Initialize the device
20    let mut accelerometer = adxl::Adxl345::new(adxl_bus);
21
22    // 3. Write default configurations (Measurement mode, standard ranges, etc.)
23    if let Err(_) = accelerometer.init_defaults() {
24        error!("Failed to initialize lh-adxl345 crate! Check wiring.");
25        return;
26    }
27
28    // Set task to run at 20Hz (every 50ms)
29    let mut ticker = Ticker::every(Duration::from_millis(50));
30
31    loop {
32        // 4. Read the raw acceleration via the accelerometer trait
33        // This blocks the CPU just long enough to pull the 6 bytes over I2C.
34        match accelerometer.read_axis() {
35            Ok((x, y, z)) => {
36                let accel_data = AccelData {
37                    raw_x: x,
38                    raw_y: y,
39                    raw_z: z,
40                    timestamp_ms: embassy_time::Instant::now().as_millis() as u32,
41                };
42
43                // Update the global telemetry Mutex
44                {
45                    let mut guard = LATEST_TELEMETRY.lock().await;
46                    //guard.accel = Some(accel_data.clone());
47                }
48
49                // Send to the SD Card logger
50                // let _ = DATA_CHANNEL.send(LogEvent::Accel(accel_data)).await;
51            }
52            Err(_) => error!("Failed to read axis from lh-adxl345 crate"),
53        }
54
55        // 7. Yield back to the Embassy executor
56        ticker.next().await;
57    }
58}