mlx90393 0.1.2

MLX90393 magnetometer driver
Documentation

MLX90393  

crates.io License Documentation

A Rust crate for the Melexis MLX90393 triaxis magnetometer sensor

https://github.com/marvinrobot42/mlx90393.git

The MLX90393 magnetometer sensor with I2C interface.

Features

  • uses embedded-hal version 1.0.x

  • async support included (see examples folder in repository for embassy-async ESP32-C6 example)

  • designed for embedded use (ESP32-C3, -C6 and -S3 and Raspberry Pi), any hardware that implements embedded-hal

  • ESP32 RISC V included in repo (and Raspberry Pi example soon)

  • an easy to use Measurements struct

  • no_std embedded compatible

  • I2C interface supported (SPI in future, may be)

  • all I2C functions available are supported by this driver

Notes

Developed using Sparkfun MLX90393 STEMMA QT (QWIIC) model: https://www.sparkfun.com/sparkfun-triple-axis-magnetometer-breakout-mlx90393-qwiic.html

The MLX90393 has a complicated I2C protocol. Considerable thought and effort was used to make the device as easy to use as possible. However, there are some idiosyncrasies that are unavoidable. If you receive an Error::CommandError Result it is mostly likely that the MLX90393 is in a measure mode that only accepts limited commands (see note below about burst mode).

  • measurement_mode: Single, Burst and WOC (Wake On Change). Single is the power on default. The read_data_by_txyz_params() and read_data_by_txyz_props functions (methods) check to see if measurement_mode is Single and if so the fn will send a start_measure_mode(MeasureMode::Single) command to get the device out of sleep and start a new measurement, so no need to explicately call start_measure_mode() before call read_data_by_XXXX(). Also, if you change the measurement mode by calling start_measurement_mode() the driver will send an Exit command because it is a requirement for the mlx90393. If using Burst mode, after calling init_device() call burst_data_rate(interval in 20 msec increments) then mlx90393.start_measurement_mode(MeasurementMode::Burst, true, true, true, true); or whatever x,y,z, and t values you need, once. Then call read_data_by_XXX when you need the field strengths or temperature. Burst mode works best with an Input pin wired to MLX90393 INT pin.

  • When using an Input pin wired to MLX90393 INT pin this driver will wait up to 2 seconds for the pin to go high, or else TIMEOUT error is returned. The max burst_data_rate (really an interval and not a rate) is 63 * 20 msec = 1260 msec.

  • note that when in burst mode the only commands the MLX90393 will accept are read_data_by_XXX() or send_exit()

  • when you call init_device() and pass the x,y,z and t bool parameters they become the driver properties values for x,y,z and t. You can read different x,y,z and t values by calling read_by_params(x, y, z, t) and pass the required x, y, z and t axis/temperature you wish to read. The MLX90393 returns 0's for the axis/temperature that are false, hence the ScaledMeasurements includes all x,y,z and t regardless of the property or parameters set/passed. It is up to you to ignore the axis/temperature values that are not being read.

  • the scaling of the measurements are done based of the datasheet according to the resolutions and hall_conf, gain_sel, temperature compensation setting you have (or defaults as per datasheet if not specifically set). The init_device() fn will set them to the defaults.

  • The new() fn takes an input pin for a parameter. If defined (a Some and not None) then it is expected that the MLX90393 INT pin is wired to your microcontroller as an INPUT type pin according to embedded_hal::digital::InputPin requirements. See the example for how to define a None option for an input pin if not defined/wired. When not defined (None) the driver will calculate the delay value required Register 0x02 parameters. If you change these values (OSR, OSR2 and DIG_FILT) the driver will store them and recalculate the required delay for new read_data_by_XXXX calls.

As stated above, the MLX90393 I2C interface is a complicated one. See the examples for the different measurement modes.

Recent version history

  • 0.1.0 Initial release

Usage


Add the dependency to Cargo.toml.

[dependencies.mlx90393]
version = "0.1"
  1. Create a hardward specific I²C driver interface and delay function
  2. Create an MLX90393 struct with the I²C interface and a delay function and an input pin (option) as parameters.
  3. Initialize the MLX90393 instance with init_device fn
  4. configure sensor if not using default values (see datasheet)

Simple Example

A more complete example is in the repository examples path

//  ESP32-C3/6 std style

use esp_idf_hal::{
    delay::{Ets, FreeRtos}, 
    gpio::*,
    i2c::{I2cConfig, I2cDriver}, io::Error, units::Hertz, 
    // prelude::*
 };

use esp_idf_hal::gpio::{Input, PinDriver};

use esp_idf_hal::delay::Delay;

use mlx90393::MLX90393;
use mlx90393::constants::DeviceAddress;
use mlx90393::data::{XYZOffset, MeasurementMode};
use anyhow::Result;
use log::*;

fn main() -> Result<()> {
  // add ESP32 esp-idf boiler plate initialization code as per Expressif here

    let pins = peripherals.pins;
    let sda = pins.gpio6; // esp32-c3  has pins.gpio0;
    let scl = pins.gpio7; // esp32-c3  haspins.gpio1;
    let i2c = peripherals.i2c0;
    //let config = I2cConfig::default(); // data rate is too high with default()
    let config = I2cConfig::new().baudrate(Hertz(100_000).into())
                        .scl_enable_pullup(true) 
                        .sda_enable_pullup(true);
    let i2c_dev = I2cDriver::new(i2c, sda, scl, &config).unwrap();
    let delay: Delay = Default::default();

    let mut drdy_pin = Some(PinDriver::input(pins.gpio18, Pull::Floating).unwrap() );  // input pin gpio18 wired to MLX90393 INT output pin

    let _no_input: Option<PinDriver<'_, Input>> = None;   // if not using the MLX90393 INT output pin for data ready function
    
    let mut mlx90393 = MLX90393::new(i2c_dev, DeviceAddress::A1_0_A0_0, delay, 
                            true, true, true, true, drdy_pin);  // with t,x,y,z enabled and stored as driver properties
    mlx90393.init_device().unwrap();  // set all config options to defaults
 
    let trig_int = mlx90393.get_trig_int().unwrap();  // wired drdy/INT pin  input pin 18 on ESP32-C6
    

    let scaled_measurements = mlx90393.read_data_by_txyz_props(MeasurementMode::Single).unwrap(); // start_measurement_mode
            // (MeasurementMode::Single) command is sent automatically for you
    info!(" scaled_measurements = {:#?}", scaled_measurements);

    loop {
        FreeRtos::delay_ms(100);
        let value = mlx90393.read_data_by_txyz_params(true, true, true, true).unwrap();
        info!("  read values = {:#?}", value);
    }

    Ok(())

}

For async set mlx90393 dependency features = ["async"] and Mlx90393::new method requires async I2C and delay

parameters. Default features is sync (blocking)

License


You are free to copy, modify, and distribute this application with attribution under the terms of either

at your option.

This project is not affiliated with nor endorsed in any way by Melexis or Adafruit or Sparkfun.