Compass

We will read the direction from an I2C compass, and log the readings to a serial port. If you have time, try displaying it on the LEDs somehow too, or use the buttons somehow.

Hints:

  • Check the documentation for the lsm303agr and microbit-v2 crates, as well as the micro:bit hardware.
  • The LSM303AGR Inertial Measurement Unit is connected to the internal I2C bus.
  • TWI is another name for I2C, so the I2C master peripheral is called TWIM.
  • The LSM303AGR driver needs something implementing the embedded_hal::i2c::I2c trait. The microbit::hal::Twim struct implements this.
  • You have a microbit::Board struct with fields for the various pins and peripherals.
  • You can also look at the nRF52833 datasheet if you want, but it shouldn’t be necessary for this exercise.

Download the exercise template and look in the compass directory for the following files.

src/main.rs:

  1. #![no_main]
  2. #![no_std]
  3. extern crate panic_halt as _;
  4. use core::fmt::Write;
  5. use cortex_m_rt::entry;
  6. use microbit::{hal::{Delay, uarte::{Baudrate, Parity, Uarte}}, Board};
  7. #[entry]
  8. fn main() -> ! {
  9.     let mut board = Board::take().unwrap();
  10.     // Configure serial port.
  11.     let mut serial = Uarte::new(
  12.         board.UARTE0,
  13.         board.uart.into(),
  14.         Parity::EXCLUDED,
  15.         Baudrate::BAUD115200,
  16.     );
  17.     // Use the system timer as a delay provider.
  18.     let mut delay = Delay::new(board.SYST);
  19.     // Set up the I2C controller and Inertial Measurement Unit.
  20.     // TODO
  21.     writeln!(serial, "Ready.").unwrap();
  22.     loop {
  23.         // Read compass data and log it to the serial port.
  24.         // TODO
  25.     }
  26. }

Cargo.toml (you shouldn’t need to change this):

  1. [workspace]
  2. [package]
  3. name = "compass"
  4. version = "0.1.0"
  5. edition = "2021"
  6. publish = false
  7. [dependencies]
  8. cortex-m-rt = "0.7.3"
  9. embedded-hal = "1.0.0"
  10. lsm303agr = "1.1.0"
  11. microbit-v2 = "0.15.1"
  12. panic-halt = "1.0.0"

Embed.toml (you shouldn’t need to change this):

  1. [default.general]
  2. chip = "nrf52833_xxAA"
  3. [debug.gdb]
  4. enabled = true
  5. [debug.reset]
  6. halt_afterwards = true

.cargo/config.toml (you shouldn’t need to change this):

  1. [build]
  2. target = "thumbv7em-none-eabihf" # Cortex-M4F
  3. [target.'cfg(all(target_arch = "arm", target_os = "none"))']
  4. rustflags = ["-C", "link-arg=-Tlink.x"]

See the serial output on Linux with:

  1. picocom --baud 115200 --imap lfcrlf /dev/ttyACM0

Or on Mac OS something like (the device name may be slightly different):

  1. picocom --baud 115200 --imap lfcrlf /dev/tty.usbmodem14502

Use Ctrl+A Ctrl+Q to quit picocom.