4.1 指南针
01-指南针 — Comprehensive Rust
译文 · 基于 Comprehensive Rust
原文链接: https://google.github.io/comprehensive-rust/exercises/bare-metal/compass.html
4.1 指南针
我们将从 I2C 指南针读取方向,并把读数记录到串口。若有时间,也可以试着在 LED 上显示,或以某种方式使用按钮。
提示:
下载练习模板,在 compass 目录中查看下列文件。
src/main.rs:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
| // Copyright 2023 Google LLC
// SPDX-License-Identifier: Apache-2.0
#![no_main]
#![no_std]
extern crate panic_halt as _;
use core::fmt::Write;
use cortex_m_rt::entry;
use microbit::{hal::{Delay, uarte::{Baudrate, Parity, Uarte}}, Board};
#[entry]
fn main() -> ! {
let mut board = Board::take().unwrap();
// 配置串口。
let mut serial = Uarte::new(
board.UARTE0,
board.uart.into(),
Parity::EXCLUDED,
Baudrate::BAUD115200,
);
// 用系统定时器作为延时提供者。
let mut delay = Delay::new(board.SYST);
// 设置 I2C 控制器与惯性测量单元。
// TODO
writeln!(serial, "Ready.").unwrap();
loop {
// 读取指南针数据并记录到串口。
// TODO
}
}
|
Cargo.toml(通常无需修改):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| [workspace]
[package]
name = "compass"
version = "0.1.0"
edition = "2024"
publish = false
[dependencies]
cortex-m-rt = "0.7.5"
embedded-hal = "1.0.0"
lsm303agr = "1.1.0"
microbit-v2 = "0.16.0"
panic-halt = "1.0.0"
|
Embed.toml(通常无需修改):
1
2
3
4
5
6
7
8
| [default.general]
chip = "nrf52833_xxAA"
[debug.gdb]
enabled = true
[debug.reset]
halt_afterwards = true
|
.cargo/config.toml(通常无需修改):
1
2
3
4
5
| [build]
target = "thumbv7em-none-eabihf" # Cortex-M4F
[target.'cfg(all(target_arch = "arm", target_os = "none"))']
rustflags = ["-C", "link-arg=-Tlink.x"]
|
在 Linux 上查看串口输出:
1
| picocom --baud 115200 --imap lfcrlf /dev/ttyACM0
|
在 Mac OS 上大致如下(设备名可能略有不同):
1
| picocom --baud 115200 --imap lfcrlf /dev/tty.usbmodem14502
|
用 Ctrl+A Ctrl+Q 退出 picocom。