This entire adventure started when I ordered 4 VL53L4CD breakout boards from DigiKey on impulse for my micromouse project. I knew it would be annoying to troubleshoot errors with python code so I decided to take this opportunity to learn Rust as well.

Usually, someone else would have already written a library for any component I need to use. The problem is, embedded rust is super bleeding-edge. The only library someone had already written was designed for the linux i2cdev crate to be run on a raspberry pi zero.

Because I didn’t want to rewrite the entire library (Spoiler: I did rewrite it), I painstakingly wrote an i2c slave device class + trait to properly run this sensor using that old library.

#![allow(dead_code)]

use core::future;

pub struct SlaveDevice<I> {
    i2c: I,
    slave_addr: u8,
}

impl<I> SlaveDevice<I>
where
    I: 
{
    pub fn new(i2c: &'a mut I2c<'a, T, M>) -> Self {
        Self {
            i2c,
            slave_addr: vl53l4cd::PERIPHERAL_ADDR as u8,
        }
    }

    pub fn new_with_addr(i2c: &'a mut I2c<'a, T, M>, addr: u8) -> Self {
        Self {
            i2c,
            slave_addr: addr,
        }
    }
}

impl<T, M> vl53l4cd::i2c::Device for SlaveDevice<'_, I2c<'_, T, M>>
where
    T: embassy_rp::i2c::Instance,
    M: embassy_rp::i2c::Mode,
{
    type Error = embassy_rp::i2c::Error;

    type Read = future::Ready<Result<(), embassy_rp::i2c::Error>>;

    type Write = future::Ready<Result<(), embassy_rp::i2c::Error>>;

    fn read(&mut self, _dest: &mut [u8]) -> Self::Read {
        future::ready(self.i2c.blocking_read(self.slave_addr, _dest))
    }

    fn write(&mut self, _data: &[u8]) -> Self::Write {
        future::ready(self.i2c.blocking_write(self.slave_addr, _data.into()))
    }
}

Now I had to face my next hurdle. I wanted to share the I2C bus with my gyroscope as well. The I2C bus can be daisychained between multiple devices but communicating on it is a shared resource. Only one thing can talk on the line at a time. I had no real idea how to do that and ended up digging up this example. Here is a snippet below:

use embassy_embedded_hal::shared_bus::i2c::I2cDevice;
use embassy_sync::mutex::Mutex;
use embassy_sync::blocking_mutex::raw::ThreadModeRawMutex;

static I2C_BUS: StaticCell<Mutex::<ThreadModeRawMutex, Twim<TWISPI0>>> = StaticCell::new();
let config = twim::Config::default();
let irq = interrupt::take!(SPIM0_SPIS0_TWIM0_TWIS0_SPI0_TWI0);
let i2c = Twim::new(p.TWISPI0, irq, p.P0_03, p.P0_04, config);
let i2c_bus = Mutex::<ThreadModeRawMutex, _>::new(i2c);
let i2c_bus = I2C_BUS.init(i2c_bus);

// Device 1, using embedded-hal-async compatible driver for QMC5883L compass
let i2c_dev1 = I2cDevice::new(i2c_bus);
let compass = QMC5883L::new(i2c_dev1).await.unwrap();

// Device 2, using embedded-hal-async compatible driver for Mpu6050 accelerometer
let i2c_dev2 = I2cDevice::new(i2c_bus);
let mpu = Mpu6050::new(i2c_dev2);

New problem, I kept finding this weird error:

mismatched types Mutex<CriticalSectionRawMutex, ...> and embassy_sync::mutex::Mutex<_, _> have similar names, but are actually distinct types perhaps two different versions of crate embassy_sync are being used?

main.rs (67, 20): arguments to this function are incorrect

mutex.rs (38, 1): Mutex<CriticalSectionRawMutex, ...> is defined in crate embassy_sync

mutex.rs (38, 1): embassy_sync::mutex::Mutex<_, _> is defined in crate embassy_sync

i2c.rs (40, 12): associated function defined here

let i2c_bus: &mut Mutex<CriticalSectionRawMutex, RefCell<I2c<'_, I2C1, Async>>> // size = 8, align = 0x8

After being stumped for over 2 days, I was disappointed with how simple the solution was. There’s a reason Rust doesn’t have a reputation of easy to learn. This error was caused purely because my embassy-embedded-hal was the nightly github build and embassy-sync was set to v0.2.0 from the cargo release. I fixed it by changing my build source with cargo.

In the process of troubleshooting this, I got in contact with the person who originally wrote that example and found that the original example was fairly outdated. There’s now a macro to simplify it.

let i2c: I2c<'_, I2C1, Async> = I2c::new_async(p.I2C1, p.PIN_3, p.PIN_2, Irqs, conf);

let i2c_bus: &Mutex<CriticalSectionRawMutex, I2c<'_, I2C1, Async>> =
    make_static!(Mutex::<CriticalSectionRawMutex, _>::new(i2c));

let i2c_dev1 = I2cDevice::new(i2c_bus);
let mut tof = Vl53l4cd::new(i2c_dev1);
tof.init(&mut Delay).await.unwrap();
tof.start_ranging(&mut Delay).await.unwrap();

let i2c_dev2 = I2cDevice::new(i2c_bus);
let mut gyro = Mpu6050::new(i2c_dev2);
gyro.init(&mut Delay).await.unwrap();

Then, I went back to figure out how to replace future.ready(i2c.blocking_read... with something async. I ended up giving up and rewrote about 60% of vl53l4cd to behave nicely with async in embassy-rs and embedded-hal-async. Find it published here.