rust-embedded
Write embedded firmware in Rust: ARM Cortex-M and RISC-V, no-std, HALs, and memory safety over C/C++. Use for IoT and safety-critical devices.
Rust Embedded
Develop embedded systems firmware with Rust for safety, performance, and modern tooling.
Quick Start
//! Blinky example for STM32 microcontroller
#![no_std]
#![no_main]
use cortex_m_rt::entry;
use panic_halt as _;
use stm32f4xx_hal::{
pac,
prelude::*,
timer::Timer,
};
use embedded_hal::digital::OutputPin;
#[entry]
fn main() -> ! {
// Get peripherals
let dp = pac::Peripherals::take().unwrap();
let cp = cortex_m::Peripherals::take().unwrap();
// Configure clocks
let rcc = dp.RCC.constrain();
let clocks = rcc.cfgr.sysclk(48.MHz()).freeze();
// Configure LED pin (PC13 on many STM32 boards)
let gpioc = dp.GPIOC.split();
let mut led = gpioc.pc13.into_push_pull_output();
// Configure timer
let mut timer = Timer::syst(cp.SYST, 1.Hz(), &clocks);
// Blink loop
loop {
led.set_high().unwrap();
timer.wait(); // 1 second delay
led.set_low().unwrap();
timer.wait();
}
}# .cargo/config.toml — Cross-compilation target
[target.thumbv7em-none-eabihf]
runner = "gdb-multiarch"
rustflags = ["-C", "link-arg=-Tlink.x", "-C", "linker=arm-none-eabi-gcc"]
[build]
target = "thumbv7em-none-eabihf"// Embedded HAL traits — abstraction for portability
use embedded_hal::{
blocking::delay::DelayMs,
digital::OutputPin,
spi::SpiDevice,
};
fn control_display<D: DelayMs<u32>, P: OutputPin>(
delay: &mut D,
reset: &mut P,
) {
reset.set_low().unwrap();
delay.delay_ms(10);
reset.set_high().unwrap();
delay.delay_ms(100);
}Key Concepts
`#![no_std]` enables bare-metal code without the standard library. The Embedded HAL provides portable hardware abstraction. `cortex-m-rt` handles vector table and startup. Use probe-rs for flashing and debugging.
When to Use
- Firmware for ARM Cortex-M, RISC-V microcontrollers
- IoT sensor nodes and actuators
- Safety-critical embedded systems
- Replacing C/C++ with memory-safe Rust
Step-by-Step
1. Pick the board/target: install `rustup target add thumbv7em-none-eabihf` for Cortex-M4F or the RISC-V equivalent.
2. Configure the linker: add `.cargo/config.toml` with `rustflags` (link.x) and default build target.
3. Scaffold a `no_std` crate: use `#![no_std]` + `#![no_main]`, add `cortex-m-rt` for startup and a panic handler.
4. Get a HAL: enable `stm32f4xx_hal` (or `nrf-hal`, `esp-hal`) peripheral features matching the chip.
5. Flash & debug: use `probe-rs`/`cargo embed` (or `openocd + gdb-multiarch`) with the target config.
6. Verify on device: blink an LED, then exercise a sensor/UART; check binary size with `cargo size`.
Examples
// Read a button and toggle an LED via embedded-hal traits
#![no_std]
#![no_main]
use cortex_m_rt::entry;
use panic_halt as _;
use stm32f4xx_hal::{pac, prelude::*, gpio::Edge};
use embedded_hal::digital::{InputPin, OutputPin};
#[entry]
fn main() -> ! {
let dp = pac::Peripherals::take().unwrap();
let rcc = dp.RCC.constrain();
let clocks = rcc.cfgr.sysclk(48.MHz()).freeze();
let gpioa = dp.GPIOA.split(&clocks);
let gpioc = dp.GPIOC.split();
let mut led = gpioc.pc13.into_push_pull_output();
let btn = gpioa.pa0.into_pull_up_input();
loop {
if btn.is_low().unwrap() {
led.set_high().unwrap();
} else {
led.set_low().unwrap();
}
cortex_m::asm::delay(100_000);
}
}# Build, flash, and inspect the binary
cargo build --release
cargo size --release
cargo embed --release # flashes via probe-rs using the target configBest Practices
- Use `no_std` crates for bare-metal targets.
- Keep memory and stack usage bounded and profiled.
- Use interrupts and DMA for I/O; avoid busy polling.
- Pin toolchain and target for reproducible builds.
- Test on hardware with a CI runner or QEMU.
- Use a RTOS (RTIC/embassy) for concurrency.
Troubleshooting
- Link errors: check target triple and memory layout.
- Stack overflow: increase stack or profile usage.
- Flaky interrupts: check priorities and critical sections.
- No output: verify the UART config and baud rate.
Validation
1. `cargo build --target thumbv7em-none-eabihf` compiles without std
2. Firmware flashes to device and runs (LED blinks)
3. UART/sensor output matches expected values
4. Binary size fits within target flash memory
Rust Embedded
Разрабатывайте прошивки для встраиваемых систем на Rust: безопасность, производительность, современный инструментарий.
Быстрый старт
//! Blinky для микроконтроллера STM32
#![no_std]
#![no_main]
use cortex_m_rt::entry;
use panic_halt as _;
use stm32f4xx_hal::{
pac,
prelude::*,
timer::Timer,
};
use embedded_hal::digital::OutputPin;
#[entry]
fn main() -> ! {
let dp = pac::Peripherals::take().unwrap();
let cp = cortex_m::Peripherals::take().unwrap();
let rcc = dp.RCC.constrain();
let clocks = rcc.cfgr.sysclk(48.MHz()).freeze();
// Настройка пина LED (PC13 на многих платах STM32)
let gpioc = dp.GPIOC.split();
let mut led = gpioc.pc13.into_push_pull_output();
let mut timer = Timer::syst(cp.SYST, 1.Hz(), &clocks);
loop {
led.set_high().unwrap();
timer.wait(); // задержка 1 секунда
led.set_low().unwrap();
timer.wait();
}
}# .cargo/config.toml — кросс-компиляция
[target.thumbv7em-none-eabihf]
runner = "gdb-multiarch"
rustflags = ["-C", "link-arg=-Tlink.x", "-C", "linker=arm-none-eabi-gcc"]
[build]
target = "thumbv7em-none-eabihf"// Embedded HAL — абстракции для переносимости
use embedded_hal::{
blocking::delay::DelayMs,
digital::OutputPin,
spi::SpiDevice,
};
fn control_display<D: DelayMs<u32>, P: OutputPin>(
delay: &mut D,
reset: &mut P,
) {
reset.set_low().unwrap();
delay.delay_ms(10);
reset.set_high().unwrap();
delay.delay_ms(100);
}Ключевые концепции
`#![no_std]` даёт bare-metal код без стандартной библиотеки. Embedded HAL — переносимые абстракции железа. `cortex-m-rt` берёт на себя vector table и startup. Для прошивки и отладки — probe-rs.
Когда использовать
- Прошивки для ARM Cortex-M, RISC-V микроконтроллеров
- IoT сенсорные узлы и приводы
- Безопасные встраиваемые системы (safety-critical)
- Замена C/C++ на memory-safe Rust
Пошаговое руководство
1. Выберите плату/таргет: `rustup target add thumbv7em-none-eabihf` для Cortex-M4F или аналог для RISC-V.
2. Настройте линкер: `.cargo/config.toml` с `rustflags` (link.x) и таргетом по умолчанию.
3. Скаффолд `no_std` крейта: `#![no_std]` + `#![no_main]`, добавьте `cortex-m-rt` для startup и panic handler.
4. Подключите HAL: включите фичи периферии `stm32f4xx_hal` (или `nrf-hal`, `esp-hal`) под чип.
5. Прошивка и отладка: используйте `probe-rs`/`cargo embed` (или `openocd + gdb-multiarch`) с конфигом таргета.
6. Проверка на устройстве: замигайте LED, затем проверьте сенсор/UART; контроль размера через `cargo size`.
Примеры
// Чтение кнопки и переключение LED через embedded-hal
#![no_std]
#![no_main]
use cortex_m_rt::entry;
use panic_halt as _;
use stm32f4xx_hal::{pac, prelude::*, gpio::Edge};
use embedded_hal::digital::{InputPin, OutputPin};
#[entry]
fn main() -> ! {
let dp = pac::Peripherals::take().unwrap();
let rcc = dp.RCC.constrain();
let clocks = rcc.cfgr.sysclk(48.MHz()).freeze();
let gpioa = dp.GPIOA.split(&clocks);
let gpioc = dp.GPIOC.split();
let mut led = gpioc.pc13.into_push_pull_output();
let btn = gpioa.pa0.into_pull_up_input();
loop {
if btn.is_low().unwrap() {
led.set_high().unwrap();
} else {
led.set_low().unwrap();
}
cortex_m::asm::delay(100_000);
}
}# Сборка, прошивка и анализ бинарника
cargo build --release
cargo size --release
cargo embed --release # прошивка через probe-rs по конфигу таргетаЛучшие практики
- `no_std` крейты для bare-metal таргетов.
- Память и стек ограничены и профилированы.
- Прерывания и DMA для I/O; без busy polling.
- Зафиксируйте toolchain и target для воспроизводимых сборок.
- Тестируйте на железе через CI-runner или QEMU.
- RTOS (RTIC/embassy) для конкурентности.
Устранение неполадок
- Ошибки линковки: проверьте target triple и layout памяти.
- Переполнение стека: увеличьте стек или профилируйте.
- Флаки прерываний: приоритеты и critical sections.
- Нет вывода: проверьте конфиг UART и baud rate.
Валидация
1. `cargo build --target thumbv7em-none-eabihf` компилируется без std
2. Прошивка загружается в устройство и работает (LED мигает)
3. Вывод UART/сенсора соответствует ожиданиям
4. Бинарник умещается во flash таргета