指南針

我們將讀取 I2C 羅盤上的方向,並將讀數記錄到序列埠。如有時間,可以試著顯示在 LED 上,或以某種方法使用按鈕。

提示:

  • 參閱 lsm303agrmicrobit-v2 Crate 的說明文件,並瞭解 micro:bit 硬體
  • LSM303AGR 慣性測量單元已連接至內部 I2C 匯流排。
  • TWI 是 I2C 的別名,所以 I2C 主周邊裝置的名稱是 TWIM。
  • LSM303AGR 驅動程式需要某個實作 embedded_hal::blocking::i2c::WriteRead 特徵的項目。microbit::hal::Twim 結構體實作此特徵。
  • 您有 microbit::Board 結構體,其中包含各種接腳和周邊裝置的欄位。
  • 您也可以視需要查看 nRF52833 規格書,但在這項練習中並非必要。

請下載練習範本,並在 compass 目錄中查看下列檔案。

src/main.rs:

#![no_main] #![no_std] extern crate panic_halt as _; use core::fmt::Write; use cortex_m_rt::entry; use microbit::{hal::uarte::{Baudrate, Parity, Uarte}, Board}; #[entry] fn main() -> ! { let board = Board::take().unwrap(); // Configure serial port. let mut serial = Uarte::new( board.UARTE0, board.uart.into(), Parity::EXCLUDED, Baudrate::BAUD115200, ); // Use the system timer as a delay provider. let mut delay = Delay::new(board.SYST); // Set up the I2C controller and Inertial Measurement Unit. // TODO writeln!(serial, "Ready.").unwrap(); loop { // Read compass data and log it to the serial port. // TODO } }

Cargo.toml (您應該不需要變更此項目):

[workspace] [package] name = "compass" version = "0.1.0" edition = "2021" publish = false [dependencies] cortex-m-rt = "0.7.3" embedded-hal = "1.0.0" lsm303agr = "0.3.0" microbit-v2 = "0.13.0" panic-halt = "0.2.0"

Embed.toml (您應該不需要變更此項目):

[default.general] chip = "nrf52833_xxAA" [debug.gdb] enabled = true [debug.reset] halt_afterwards = true

.cargo/config.toml (您應該不需要變更此項目):

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

使用下列指令在 Linux 查看序列輸出內容:

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

或在 macOS 上使用類似如下的指令 (裝置名稱可能略有不同):

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

按下 Ctrl + A、Ctrl + Q 鍵即可退出 picocom。