Command Palette

Search for a command to run...

Назад к скиллам
скилл № 37600

bare-metal-rust

Use when the user asks about embedded Rust, no_std firmware, Cortex-M Rust, embedded-hal, PAC and svd2rust, RTIC, Embassy, probe-rs or defmt. Produces no_std…

БесплатноБез исполняемых скриптов
j4flmaoот j4flmao★ 47 звёзд на GitHub

Установить bare-metal-rust в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Об этом скилле

Bare-Metal Rust

Purpose

Rust removes whole classes of firmware bugs (buffer overruns, use-after-free, data races between ISR and main) at compile time while compiling to code comparable with C. This skill shows how to structure a no_std project, share state with interrupts soundly, pick between RTIC, Embassy and a plain superloop, and build/flash/debug with the standard toolchain.

Agent Protocol

Trigger

"embedded rust", "no_std", "cortex-m rust", "embedded-hal", "PAC", "svd2rust", "RTIC", "Embassy", "probe-rs", "defmt".

Input Context

  • MCU family and existing HAL crate (e.g. stm32f4xx-hal, nrf-hal, rp2040-hal/embassy-rp, esp-hal)
  • Concurrency model wanted (superloop, RTIC, Embassy async)
  • Memory budget and whether an allocator is acceptable

Output Artifact

Rust code (main.rs, Cargo.toml, memory.x, .cargo/config.toml) or a review. No file unless requested.

Response Format

Target: {thumbv7em-none-eabihf | riscv32imac-unknown-none-elf | ...}
Stack: {PAC/HAL crate versions} + {RTIC | Embassy | superloop}
Shared state: {mechanism and why it is sound}
Code: {snippet}
Build/flash: {commands}

1. The no_std Environment

  • #![no_std] links only core (and optionally alloc if you provide a #[global_allocator]). No threads, files, or heap by default.
  • #![no_main] + cortex-m-rt's #[entry] provide the reset handler, vector table and memory.x linker layout.
  • You must supply a panic handler: panic-halt, panic-probe (with defmt), or your own #[panic_handler].
#![no_std]
#![no_main]

use cortex_m_rt::entry;
use panic_halt as _;

#[entry]
fn main() -> ! {
    let dp = pac::Peripherals::take().unwrap();   // singleton: second take() returns None
    // configure clocks/GPIO via the HAL ...
    loop {
        cortex_m::asm::wfi();                     // sleep until an interrupt
    }
}

main returns ! — firmware never returns.

2. Crate Layers

Layer What it is Example
PAC (Peripheral Access Crate) Generated by svd2rust from the vendor SVD; register-level, mostly unsafe writes of raw bits are wrapped in typed field APIs stm32f4, nrf52840-pac
HAL Safe drivers implementing embedded-hal traits stm32f4xx-hal, nrf52840-hal, esp-hal
embedded-hal 1.0 Portable traits (digital::OutputPin, spi::SpiDevice, i2c::I2c, delay::DelayNs); embedded-hal-async for async stable since Jan 2024
BSP Board pin mapping on top of the HAL microbit-v2
Drivers Device drivers generic over the traits sensor crates

Write drivers against embedded-hal traits so they run on any HAL.

3. Sharing State with Interrupts

static mut requires unsafe for every access, and in the 2024 edition creating references to it is denied by default (static_mut_refs). Use one of:

  1. critical-section Mutex — portable, short critical sections:
use core::cell::RefCell;
use critical_section::Mutex;

static COUNTER: Mutex<RefCell<u32>> = Mutex::new(RefCell::new(0));

#[interrupt]
fn TIM2() {
    critical_section::with(|cs| *COUNTER.borrow_ref_mut(cs) += 1);
}

fn read_counter() -> u32 {
    critical_section::with(|cs| *COUNTER.borrow_ref(cs))
}

The CriticalSection token proves interrupts are masked (single core) while borrowing. Provide an implementation via cortex-m's critical-section-single-core feature or your HAL.

  1. Atomics (core::sync::atomic) for single words — no masking. Cortex-M0/M0+ lacks CAS (fetch_add etc.); use portable-atomic there.
  2. RTIC resources — compile-time priority-ceiling locking (below).
  3. Embassy channels/signals (embassy-sync) between async tasks and interrupts.

4. Concurrency Frameworks

Option Model Choose when
Superloop + interrupts loop { wfi } + ISRs very small programs
RTIC 2 Hardware tasks bound to interrupts, software tasks, Stack Resource Policy (priority ceiling) — deadlock-free, no runtime scheduler hard real-time with static priorities; analysable timing
Embassy async/await executor, async HALs (embassy-stm32, embassy-nrf, embassy-rp), timers, networking (embassy-net), USB, BLE via nrf-softdevice/trouble I/O-heavy firmware, many concurrent waits, low power
RTOS bindings FreeRTOS/Zephyr with Rust mixing with existing C RTOS code

5. Memory Without a Heap

  • heapless::{Vec, String, spsc::Queue, pool} — fixed capacity in the type (heapless::Vec<u8, 64>).
  • static_cell::StaticCell to obtain &'static mut buffers once at startup (common with Embassy).
  • If alloc is truly needed, use embedded-alloc with a static arena and handle allocation failure.
  • Check stack usage: flip-link puts the stack below .data/.bss so overflow faults instead of silently corrupting statics.

6. Toolchain

# .cargo/config.toml
[build]
target = "thumbv7em-none-eabihf"      # Cortex-M4F/M7

[t
Полный SKILL.md на GitHub

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл bare-metal-rust?

Use when the user asks about embedded Rust, no_std firmware, Cortex-M Rust, embedded-hal, PAC and svd2rust, RTIC, Embassy, probe-rs or defmt. Produces no_std firmware with safe interrupt sharing and a flash/debug toolchain. Not for general Rust application code (use lang-rust) or C firmware (use c-cpp-patterns).

Как установить скилл bare-metal-rust?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл bare-metal-rust запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить bare-metal-rust с