embedded-rust について
組み込み Rust ファームウェア開発をエージェント向けに案内するスキルです。セットアップ、書き込み、デバッグ、ログ、並行処理、パニック処理を扱い、probe-rs、defmt、RTIC、no_std の手順をまとめています。
主な機能
- 01no_std ファームウェアの設定
- 02probe-rs による書き込みとデバッグ
- 03defmt 構造化ログの追加
- 04RTIC による割り込み駆動の並行処理
- 05パニックハンドラーの選択
活用シーン
- 01MCU へのファームウェア書き込み
- 02組み込み Rust プログラムのデバッグ
- 03デバッグプローブ経由の簡潔なログ出力
- 04no_std ファームウェアの並行処理とパニック対応
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ mohitmishra786/ low-level-dev-skills --skill embedded-rustインストール後、Claude Code で/embedded-rustを入力して読み込まれたか確認します。
同梱ファイルreferences/embedded-rust-targets.md
詳細
組み込み Rust
目的
probe-rs/cargo-embed によるフラッシュ書き込みとデバッグ、defmt による構造化ログ、RTIC 並行処理フレームワーク、cortex-m-rt の起動処理、no_std の構成、パニックハンドラーの選択など、組み込み Rust 開発をエージェントが進めるためのガイドです。
トリガー
- 「Rust ファームウェアを MCU に書き込むにはどうすればよいですか?」
- 「組み込み Rust プログラムをデバッグするにはどうすればよいですか?」
- 「組み込み Rust でログ記録に defmt を使うにはどうすればよいですか?」
- 「割り込み駆動の並行処理に RTIC を使うにはどうすればよいですか?」
- 「組み込み Rust における #![no_std] #![no_main] とは何ですか?」
- 「no_std の組み込み Rust でパニックを処理するにはどうすればよいですか?」
ワークフロー
1. プロジェクトのセットアップ
# Cargo.toml
[package]
name = "my-firmware"
version = "0.1.0"
edition = "2021"
[dependencies]
cortex-m = { version = "0.7", features = ["critical-section-single-core"] }
cortex-m-rt = "0.7"
defmt = "0.3"
defmt-rtt = "0.4"
panic-probe = { version = "0.3", features = ["print-defmt"] }
# Embassy (async embedded) — alternative to RTIC
# embassy-executor = { version = "0.5", features = ["arch-cortex-m"] }
[profile.release]
opt-level = "s" # size optimization for embedded
lto = true
codegen-units = 1
debug = true # keep debug info for defmt/probe-rs
# .cargo/config.toml
[build]
target = "thumbv7em-none-eabihf" # Cortex-M4F / M7
[target.thumbv7em-none-eabihf]
runner = "probe-rs run --chip STM32F411CEUx" # auto-run after build
rustflags = ["-C", "link-arg=-Tlink.x"] # cortex-m-rt linker script
2. 最小限のベアメタルプログラム
// src/main.rs
#![no_std]
#![no_main]
use cortex_m_rt::entry;
use defmt::info;
use defmt_rtt as _; // RTT transport for defmt
use panic_probe as _; // panic handler that prints via defmt
#[entry]
fn main() -> ! {
info!("Booting up!");
// Access peripherals via PAC or HAL
let _core = cortex_m::Peripherals::take().unwrap();
// let dp = stm32f4xx_hal::pac::Peripherals::take().unwrap();
loop {
info!("Running...");
cortex_m::asm::delay(8_000_000); // rough delay
}
}
一般的な MCU のターゲットトリプル:
| MCU ファミリー | ターゲットトリプル |
|---|---|
| Cortex-M0/M0+ | thumbv6m-none-eabi |
| Cortex-M3 | thumbv7m-none-eabi |
| Cortex-M4(FPU なし) | thumbv7em-none-eabi |
| Cortex-M4F / M7 | thumbv7em-none-eabihf |
| Cortex-M33 | thumbv8m.main-none-eabihf |
| RISC-V RV32IMAC | riscv32imac-unknown-none-elf |
rustup target add thumbv7em-none-eabihf
3. probe-rs — フラッシュ書き込みとデバッグ
# Install probe-rs
curl --proto '=https' --tlsv1.2 -LsSf https://github.com/probe-rs/probe-rs/releases/latest/download/probe-rs-tools-installer.sh | sh
# Flash firmware
probe-rs run --chip STM32F411CEUx target/thumbv7em-none-eabihf/release/firmware
# Interactive debug session
probe-rs debug --chip STM32F411CEUx target/thumbv7em-none-eabihf/release/firmware
# List connected probes
probe-rs list
# Supported chips
probe-rs chip list | grep STM32
cargo を使う場合:
# Using the runner in .cargo/config.toml
cargo run --release # builds, flashes, and streams defmt logs
cargo build --release # build only
4. defmt — 効率的なログ記録
defmt(デフォーマッター)はログ文字列を整数にエンコードし、最小限のバイト数で送信して、ホスト側でデコードします:
use defmt::{info, warn, error, debug, trace, Format};
// Basic logging
info!("Temperature: {} °C", temp);
warn!("Stack usage: {}/{}", used, total);
error!("I2C error: {:?}", err);
// Derive Format for custom types
#[derive(Format)]
struct Packet { id: u8, len: u16 }
info!("Received: {:?}", pkt);
// Assertions (panic with defmt message)
defmt::assert_eq!(result, expected);
defmt::assert!(condition, "message with {}", value);
defmt バックエンド(いずれか 1 つを選択):
# RTT (fastest, needs debug probe connected)
defmt-rtt = "0.4"
# Semihosting (slower, works without RTT support)
defmt-semihosting = "0.1"
5. RTIC — リアルタイム割り込み駆動型並行処理
// Cargo.toml
// rtic = { version = "2", features = ["thumbv7-backend"] }
#[rtic::app(device = stm32f4xx_hal::pac, peripherals = true, dispatchers = [SPI1])]
mod app {
use stm32f4xx_hal::{pac, prelude::*};
use defmt::info;
#[shared]
struct Shared {
counter: u32,
}
#[local]
struct Local {}
#[init]
fn init(cx: init::Context) -> (Shared, Local) {
info!("RTIC init");
periodic_task::spawn().unwrap();
(Shared { counter: 0 }, Local {})
}
#[task(shared = [counter])]
async fn periodic_task(mut cx: periodic_task::Context) {
loop {
cx.shared.counter.lock(|c| *c += 1);
info!("Count: {}", cx.shared.counter.lock(|c| *c));
rtic_monotonics::systick::Systick::delay(500.millis()).await;
}
}
#[task(binds = EXTI0, local = [], priority = 2)]
fn button_isr(cx: button_isr::Context) {
info!("Button pressed!");
}
}
6. パニックハンドラー
| クレート | 動作 | 使用する場面 |
|---|---|---|
panic-halt | 無限ループ | 本番環境、デバッグプローブなし |
panic-probe | defmt メッセージを出力して停止 | probe-rs を使った開発 |
panic-semihosting | GDB セミホスティング出力 | GDB を使った開発 |
panic-reset | ハードリセット | ウォッチドッグ型の復旧 |
# Choose exactly one panic handler
[dependencies]
panic-halt = "0.2" # or:
panic-probe = { version = "0.3", features = ["print-defmt"] }
組み込み Rust のターゲットトリプルについては、references/embedded-rust-targets.md を参照してください。
関連スキル
- probe-rs の代替となる OpenOCD ベースのデバッグには、
skills/embedded/openocd-jtagを使用してください #![no_std]のパターンと制約については、skills/rust/rust-no-stdを使用してください- メモリレイアウトの設定には、
skills/embedded/linker-scriptsを使用してください - クロスコンパイルのツールチェーンのセットアップには、
skills/rust/rust-crossを使用してください
コメント
Markdown 対応