Skip to main content

r_d_inclita_sofware/sensors/
ms5611.rs

1use crate::telemetry::data::{AltimeterData, DATA_CHANNEL, LATEST_TELEMETRY, LogEvent};
2
3use defmt::{error, info};
4use embassy_stm32::gpio::Output;
5use embassy_stm32::spi::Spi;
6use embassy_time::{Delay, Instant, Timer};
7use embedded_hal_bus::spi::ExclusiveDevice;
8use ms5611_rs::{Ms5611, Oversampling};
9
10#[embassy_executor::task]
11pub async fn ms5611_task(
12    spi_bus: Spi<'static, embassy_stm32::mode::Async, embassy_stm32::spi::mode::Master>,
13    cs_pin: Output<'static>,
14) {
15    info!("Starting MS5607 Altimeter Task (50Hz)...");
16
17    let spi_device = match ExclusiveDevice::new(spi_bus, cs_pin, Delay) {
18        Ok(device) => device,
19        Err(_) => {
20            error!("Failed to initialize SPI ExclusiveDevice for  Altimeter");
21            return;
22        }
23    };
24    let mut sensor = Ms5611::new_spi(spi_device);
25    let mut delay = Delay;
26
27    // Read the factory calibration PROM from the sensor
28    if let Err(_) = sensor.init(&mut delay).await {
29        error!("Failed to initialize MS5607!");
30        loop {
31            Timer::after_secs(1).await;
32        } // Halt task on failure
33    }
34
35    info!("MS5607 Calibrated! Starting conversion loop...");
36
37    loop {
38        // Osr4096 is max resolution. The .await here allows Embassy to pause
39        // THIS task for 9ms and go run the BNO055, Zero wasted CPU.
40        match sensor.measure(Oversampling::Osr4096, &mut delay).await {
41            Ok(measurement) => {
42                let data = AltimeterData {
43                    timestamp_ms: Instant::now().as_millis() as u32,
44                    pressure: measurement.pressure_mbar,
45                    temperature: measurement.temperature_c,
46                    altitude: 0.0,
47                };
48                info!(" MS {:?}", data);
49                // Wrap it and send it!
50                DATA_CHANNEL.send(LogEvent::Baro(data.clone())).await;
51                {
52                    let mut guard = LATEST_TELEMETRY.lock().await;
53                    guard.baro = Some(data.into());
54                }
55            }
56            Err(_) => error!("MS5607 read failed!"),
57        }
58        // Run at 50Hz (every 20ms)
59        Timer::after_millis(20).await;
60    }
61}