transitioning sensor reads to second core

This commit is contained in:
Andy Killorin 2025-01-18 13:10:07 -05:00
commit 7a918e2b65
Signed by: ank
GPG key ID: 23F9463ECB67FE8C

View file

@ -0,0 +1,102 @@
use core::sync::atomic::{AtomicU8, Ordering};
use core::task::Poll;
use core::{cell::RefCell, mem::transmute};
use embassy_executor::Executor;
use embassy_rp::peripherals::{I2C0, I2C1};
use embassy_time::{Delay, Duration, Instant, Timer};
use embassy_rp::gpio::Output;
use embassy_rp::i2c::{Async, I2c};
use embedded_hal_bus::i2c::RefCellDevice;
use log::info;
use mpu6050::Mpu6050;
use nalgebra::Vector3;
pub struct SensorHardware {
bus_tof: I2c<'static, I2C1, Async>,
bus_gyro: I2c<'static, I2C0, Async>,
tof2enable: Output<'static>,
}
pub fn sensor_manager(mut hardware: SensorHardware) -> ! {
let executor = Executor::new();
let executor: &'static mut Executor = unsafe{transmute(&executor)};
executor.run(move |spawner| {
spawner.spawn(init_sensors(hardware)).unwrap();
});
}
static POLL_STATE: AtomicU8 = AtomicU8::new(PollState::None as u8);
#[repr(u8)]
enum PollState {
None,
Tof1,
Tof2,
Gyro,
}
struct SensorData {
/// distance, mm
tof1: Option<u16>,
/// distance, mm
tof2: Option<u16>,
/// acceleration, rad/s
gyro: Option<Vector3<f32>>,
/// acceleration, g
accel: Option<Vector3<f32>>,
updated: Instant,
}
#[embassy_executor::task]
async fn init_sensors(mut hardware: SensorHardware) {
let bus = RefCell::new(hardware.bus_tof);
Timer::after_millis(1).await;
let mut tof = vl53l0x::VL53L0x::new(RefCellDevice::new(&bus)).unwrap();
tof.set_address(0x32).unwrap();
hardware.tof2enable.set_high();
Timer::after_micros(1200).await; // DS11555 3.2
let mut tof2 = vl53l0x::VL53L0x::new(RefCellDevice::new(&bus)).unwrap();
let mut gyro = Mpu6050::new_with_addr(hardware.bus_gyro,0x68);
gyro.init(&mut Delay).unwrap();
gyro.set_gyro_range(mpu6050::device::GyroRange::D2000).unwrap();
gyro.set_accel_range(mpu6050::device::AccelRange::G16).unwrap();
let mut data = SensorData {
tof1: None,
tof2: None,
gyro: None,
accel: None,
updated: Instant::now(),
};
loop {
POLL_STATE.store(PollState::Tof1 as u8, Ordering::SeqCst);
if let Ok(dist) = tof.read_range_single_millimeters_blocking() {
info!("dist1: {dist}mm");
data.tof1 = Some(dist);
}
Timer::after_millis(3).await;
POLL_STATE.store(PollState::Tof2 as u8, Ordering::SeqCst);
if let Ok(dist) = tof2.read_range_single_millimeters_blocking() {
info!("dist2: {dist}mm");
data.tof2 = Some(dist);
}
Timer::after_millis(3).await;
POLL_STATE.store(PollState::Gyro as u8, Ordering::SeqCst);
if let Ok(gyro) = gyro.get_gyro() {
info!("rotation: {gyro}");
data.gyro = Some(gyro);
}
if let Ok(accel) = gyro.get_acc() {
data.accel = Some(accel);
}
POLL_STATE.store(PollState::None as u8, Ordering::SeqCst);
}
}