Skip to main content
CodeSpeedTest
Languages
Start TypingJump into a test — pick any languageAdaptive TrainingUnlock chars as you master themPractice DrillsFocused sessions targeting weak spotsDaily ChallengesNew coding challenges every dayRace ModeCompete against others in real timeAI OpponentRace against an AI at your WPM levelTournamentsLive coding speed tournamentsArcade GamesZType, Overkill Survival, Glyphica & moreGamificationXP, coins, badges & quests
LeaderboardGlobal rankings for every languageCertificatesEarn verifiable Bronze / Silver / Gold certsActivityDaily streaks & historical analyticsProfileYour stats, badges & achievements
Browse Languages500+ languages with real code examplesBlogTips, guides & deep divesFree ToolsWPM calculator, typing speed report & moreFAQCommon questions answeredGetting StartedNew to CodeSpeedTest?AboutOur story & missionSupportGet help — Pro users get priorityContactGet in touch with the team
Pricing
  1. Home
  2. /
  3. Learn
  4. /
  5. Embedded-rust

Learn Embedded-rust - 3 Code Examples & CST Typing Practice Test

Embedded Rust refers to using the Rust programming language to develop software for embedded systems, microcontrollers, and resource-constrained devices. It focuses on safety, performance, and concurrency without relying on runtime environments or garbage collection.

View all 3 Embedded-rust code examples →
Blink an LEDRead Analog SensorControl Servo Motor

Learn EMBEDDED-RUST with Real Code Examples

Updated Nov 27, 2025

Explain

Rust provides memory safety without a garbage collector, making it ideal for embedded systems where reliability is critical.

Embedded Rust allows programming directly on microcontrollers and hardware with low-level control.

Supports concurrency and real-time programming through Rust's ownership and type system.

Integrates with hardware abstraction layers (HALs) and peripheral access crates (PACs) for device-specific programming.

Widely used in IoT, robotics, automotive, aerospace, and safety-critical embedded applications.

Core Features

Ownership and borrowing system ensures safe memory usage

No garbage collector, suitable for bare-metal systems

Embedded-friendly crates like `embedded-hal`, `cortex-m`, `rtic`

Support for no_std environments

Integration with Rust tooling (Cargo, rustfmt, Clippy)

Basic Concepts Overview

Ownership, borrowing, and lifetimes - memory safety concepts

no_std - building without standard library for embedded targets

HAL - hardware abstraction layer for peripherals

PAC - peripheral access crate for device registers

RTIC - real-time interrupt-driven concurrency framework

Project Structure

Cargo.toml - project configuration and dependencies

src/main.rs - main firmware entry point

src/lib.rs - optional library modules

boards/ or examples/ - board-specific code

Tests/ - unit tests, if supported on embedded targets

Building Workflow

Write Rust code targeting a microcontroller

Use HAL/PAC crates for peripheral control

Compile using appropriate target triple

Flash the firmware onto the device

Debug and monitor using hardware debug probes

Difficulty Use Cases

Beginner: Blink an LED on a microcontroller

Intermediate: Read sensors and send data via UART or I2C

Advanced: Implement RTIC-based multitasking

Expert: Develop safety-critical, real-time firmware

Architect: Build scalable embedded applications with multiple subsystems

Comparisons

Embedded Rust vs C/C++: safer memory handling, modern tooling, zero-cost abstractions

Embedded Rust vs MicroPython: Rust is compiled, faster, and memory safe; MicroPython is interpreted and easier for rapid prototyping

Embedded Rust vs Arduino C: Rust offers concurrency safety and modern language features

Embedded Rust vs Go TinyGo: Rust has finer control over hardware and better real-time capabilities

Embedded Rust vs Zephyr RTOS C apps: Rust can run bare-metal or with RTOS, but benefits from memory safety and modern syntax

Versioning Timeline

2010 - Rust language created by Mozilla

2015 - Rust 1.0 stable release

2017 - Initial Embedded Rust community formation

2018 - `embedded-hal` standardized HAL traits

2019 - `cortex-m` and `RTIC` frameworks widely adopted

2021 - Major growth in microcontroller support

2025 - Embedded Rust increasingly used in industrial and safety-critical applications

Glossary

HAL - Hardware Abstraction Layer

PAC - Peripheral Access Crate

no_std - compile without Rust standard library

RTIC - Real-Time Interrupt-driven Concurrency framework

Embedded Rust - Rust for microcontrollers and bare-metal devices

Installation Setup

Install Rust via rustup

Add target for the microcontroller (e.g., `thumbv7em-none-eabihf`)

Install `cargo-binutils` and `probe-rs` for flashing/debugging

Set up project structure with `cargo new --lib` or `cargo new --bin`

Test with a simple blinky example to validate setup

Environment Setup

Install Rust via rustup

Add target for microcontroller

Install embedded tools (probe-rs, cargo-binutils)

Clone/initialize project with Cargo

Test with a basic LED blink example

Config Files

Cargo.toml - Rust project configuration

src/main.rs - main firmware entry

src/lib.rs - library modules

boards/ - board-specific configurations

.cargo/config.toml - target and toolchain config

Optional examples/ and tests/

Cli Commands

cargo build --target <target> - Compile for embedded target

cargo run - Run on host (for simulation/testing)

cargo flash - Flash firmware to device via probe

cargo test - Run unit tests

probe-rs debug - Debug microcontroller via probe

Internationalization

Documentation in English primarily

Comments and code can follow any locale

Crates support multiple locales where applicable

Embedded hardware is language-agnostic

Community translations growing

Accessibility

Accessible via open-source Rust tooling

Remote flashing and debugging possible via probes

Documentation and examples widely available

Cross-platform host tooling (Linux, macOS, Windows)

Community resources for learning and troubleshooting

Ui Styling

Minimal; usually no UI in bare-metal

Optional LEDs, displays, or serial console for feedback

RTIC tasks may trigger outputs to indicators

Embedded dashboards possible with external devices

Visualization typically offloaded to host or cloud

State Management

Variables and peripherals managed via ownership

RTIC or interrupt-driven frameworks manage task state

no_std requires explicit memory handling

Static variables used for global device state

Peripheral access through safe Rust abstractions

Data Management

Direct memory access via PAC registers

Buffers and arrays for sensor/actuator data

Persistent storage via flash or EEPROM

Host communication via UART/SPI/I2C

Data logging via semihosting or RTT for debugging

Architecture

Bare-metal runtime without OS for microcontrollers

HALs abstracting peripheral access

Device-specific PACs for register-level control

Optional real-time frameworks like RTIC for scheduling

Cargo and Rust tooling manage compilation, dependencies, and flashing

Rendering Model

Bare-metal firmware compiled to target binary

HAL/PAC provide hardware access without OS

RTIC or async frameworks manage concurrency

Cargo manages dependencies and cross-compilation

Binary flashed to microcontroller via probe or bootloader

Architectural Patterns

No_std bare-metal design

Modular peripheral abstraction (HAL/PAC)

Event-driven or RTIC concurrency

Safe interaction with hardware through Rust types

Optional FFI integration with C/C++ libraries

Real World Architectures

IoT sensor nodes with BLE or LoRa communication

Robotics firmware controlling motors and sensors

Automotive embedded systems for control units

Industrial IoT monitoring and control devices

Wearable devices with real-time performance

Design Principles

Memory safety without garbage collection

Zero-cost abstractions for performance

Concurrency safety with ownership and type system

No standard library for bare-metal environments

Strong ecosystem for embedded hardware support

Scalability Guide

Modularize firmware for multiple boards

Optimize memory usage for larger applications

Use RTIC for concurrent task scheduling

Leverage async or DMA for high-throughput communication

Split code into crates for maintainability

Migration Guide

Update Cargo.toml dependencies

Check HAL/PAC versions with microcontroller support

Adapt code to new Rust compiler versions

Test RTIC or async task handling

Verify flashing and debug processes with updated tools

Performance Notes

Use `no_std` to reduce binary size

Minimize heap allocations, prefer stack or static memory

Optimize interrupt handlers and task execution time

Leverage inline functions and zero-cost abstractions

Profile with hardware timers if precise timing is required

Security Notes

Memory safety is largely enforced by Rust

Avoid unsafe blocks unless necessary and review carefully

Ensure firmware authenticity when flashing

Control access to debug interfaces

Protect communication channels (encryption, authentication)

Monitoring Analytics

Use semihosting or RTT for real-time logging

Monitor task timing and latency

Analyze memory footprint and stack usage

Log peripheral data for debugging

Audit firmware for safety and correctness

Code Quality

Use Rust idiomatic patterns and safe abstractions

Comment critical hardware interactions

Unit test where possible, host simulation for logic

Modularize HAL/PAC interactions

Regularly run Clippy and Rustfmt

Practical Examples

Blinking LED with no_std

Reading temperature and humidity sensors

Controlling servo motors or stepper motors

Implementing RTIC for concurrent tasks

UART, SPI, or I2C communication with peripherals

Troubleshooting

Check target architecture matches microcontroller

Ensure HAL/PAC versions are compatible with Rust version

Verify flashing/debugging setup (probe-rs, OpenOCD)

Use `cargo build --target <target>` for embedded compilation

Debug with logging via semihosting or RTT if available

Testing Guide

Test peripheral drivers in isolation

Use hardware-in-the-loop (HIL) testing for real-time behavior

Leverage unit tests where possible on host

Validate interrupt handling and concurrency safety

Simulate embedded environment using emulators if available

Deployment Options

Flash firmware to microcontrollers via debug probes

Deploy OTA updates for IoT devices

Package multiple binaries for different targets

Use CI/CD pipelines for automated builds

Integrate with embedded OSes if applicable

Tools Ecosystem

Rust compiler (rustc) and Cargo build system

Embedded HAL crates (embedded-hal, stm32f4xx-hal, nrf-hal, etc.)

probe-rs, OpenOCD for debugging and flashing

RTIC framework for real-time scheduling

Unit testing and CI/CD via cargo-embedded workflows

Integrations

Communication with sensors via I2C, SPI, UART

Peripheral drivers via HAL/PAC crates

Wireless protocols: BLE, LoRa, Zigbee via Rust crates

Integration with Rust server/cloud backends for IoT

Optional integration with C/C++ libraries using FFI

Productivity Tips

Leverage HAL and PAC crates to reduce boilerplate

Use RTIC for predictable concurrency

Modularize code for multiple boards

Automate builds and flashing with Cargo

Document peripheral usage clearly

Challenges

Learning ownership and lifetimes in low-level programming

Debugging bare-metal firmware without OS support

Cross-compilation and toolchain configuration

Limited debugging tools on resource-constrained devices

Integrating multiple concurrent tasks safely

Learning Path

Learn Rust basics: ownership, lifetimes, types, concurrency

Understand `no_std` and memory-constrained programming

Explore embedded HAL and PAC crates

Write small firmware for LEDs, buttons, and sensors

Advance to RTIC, concurrency, and IoT device development

Skill Improvement Plan

Week 1: Rust syntax, ownership, and memory management

Week 2: Compile for `no_std`, learn HALs

Week 3: Flash and debug simple microcontroller projects

Week 4: Implement real-time tasks with RTIC

Week 5: Integrate communication peripherals and IoT features

Interview Questions

What are the advantages of Embedded Rust over C/C++?

Explain `no_std` and why it's important in embedded systems.

How do you interface Rust with hardware peripherals?

Describe concurrency management in embedded Rust (RTIC).

What are common pitfalls when programming microcontrollers with Rust?

Cheat Sheet

cargo build --target <target> - compile for embedded target

cargo run - run on host for testing

#![no_std] - compile without standard library

#![no_main] - no standard main function, for embedded entry

cortex_m::asm::delay(n) - busy wait for n cycles

Books

The Embedded Rust Book

Programming Embedded Systems in Rust

Hands-On Embedded Rust Projects

Real-Time Systems with Embedded Rust

Rust for Microcontrollers and IoT

Tutorials

Getting Started with Embedded Rust

Blinking LEDs and GPIO control

UART, SPI, and I2C communication

RTIC Concurrency and Real-Time Programming

Building IoT Projects with Embedded Rust

Official Docs

https://www.rust-lang.org/embedded

https://docs.rust-embedded.org/book/

https://docs.rs/embedded-hal/

https://rtic.rs/

https://probe-rs.github.io/probe-rs/

Community Links

Rust Embedded Working Group

Reddit r/rust and r/embedded

Rust Embedded Discord

GitHub repositories for HAL/PAC crates

Technical blogs and video tutorials

Community Support

The Embedded Rust community (https://www.rust-embedded.org/)

Rust Embedded Working Group GitHub

Reddit r/rust and r/embedded

Crates.io embedded-specific packages

Rust Users Forum and Discord channels

Monetization

Firmware consulting for embedded systems

IoT device development and prototyping

Industrial embedded systems development

Training courses on Embedded Rust

Custom embedded software solutions

Future Roadmap

Expanded microcontroller and SoC support

Improved debugging and tracing tools

Integration with real-time OSes

Better async/await support for embedded targets

Broader industrial adoption and standardization

When Not To Use

When working with extremely resource-limited devices (<8KB flash) and Rust compilation overhead is unacceptable

For rapid prototyping where interpreted languages are faster to iterate

When existing C/C++ libraries are required without FFI adaptation

For legacy hardware with no Rust ecosystem support

When developer team has no Rust experience and timeline is strict

Final Summary

Embedded Rust brings memory-safe, high-performance programming to microcontrollers and embedded systems.

Supports bare-metal, `no_std` development with modern tooling and concurrency safety.

Widely applicable in IoT, robotics, and safety-critical devices.

Integration with HALs, PACs, and RTIC frameworks enables reliable low-level firmware.

Growing ecosystem and community make it increasingly viable for production embedded development.

Faq

Do I need a Rust license? -> No, Rust is open-source and free.

Can I use Embedded Rust on any microcontroller? -> Depends on target support and available HAL/PAC crates.

Is debugging harder in Embedded Rust? -> Slightly, but probe-rs and RTT tools help.

Does Rust perform well on microcontrollers? -> Yes, with zero-cost abstractions and careful memory management.

Can I use C libraries with Embedded Rust? -> Yes, via Rust FFI.

Code Sample Descriptions

1

Blink an LED

#![no_std]
#![no_main]

use panic_halt as _;
use cortex_m_rt::entry;
use stm32f4xx_hal::{prelude::*, stm32};

#[entry]
fn main() -> ! {
    let dp = stm32::Peripherals::take().unwrap();
    let gpiod = dp.GPIOD.split();
    let mut led = gpiod.pd12.into_push_pull_output();

    loop {
        led.toggle().unwrap();
        cortex_m::asm::delay(8_000_000);
    }
}

Toggle an LED on pin 13 every 500 ms using Embedded Rust.

Let’s Try →
2

Read Analog Sensor

#![no_std]
#![no_main]

use panic_halt as _;
use cortex_m_rt::entry;
use stm32f4xx_hal::{adc::Adc, prelude::*, serial::Serial, stm32};

#[entry]
fn main() -> ! {
    let dp = stm32::Peripherals::take().unwrap();
    let mut adc = Adc::adc1(dp.ADC1, true);
    let mut serial = Serial::usart2(dp.USART2, ...);

    loop {
        let value: u16 = adc.read(&mut dp.GPIOA.pa0).unwrap();
        writeln!(serial, "ADC value: {}", value).unwrap();
    }
}

Read a potentiometer value from an ADC pin and print via serial.

Let’s Try →
3

Control Servo Motor

#![no_std]
#![no_main]

use panic_halt as _;
use cortex_m_rt::entry;
use stm32f4xx_hal::{prelude::*, pwm, stm32};
use cortex_m::asm::delay;

#[entry]
fn main() -> ! {
    let dp = stm32::Peripherals::take().unwrap();
    let pwm_pin = ...; // configure PWM for servo
    loop {
        for duty in 40..=115 {
        pwm_pin.set_duty(duty);
        delay(1_000_000);
        }
        for duty in (40..=115).rev() {
        pwm_pin.set_duty(duty);
        delay(1_000_000);
        }
    }
}

Sweep a servo motor using PWM on pin D9.

Let’s Try →

Frequently Asked Questions about Embedded-rust

What is Embedded-rust?

Embedded Rust refers to using the Rust programming language to develop software for embedded systems, microcontrollers, and resource-constrained devices. It focuses on safety, performance, and concurrency without relying on runtime environments or garbage collection.

What are the primary use cases for Embedded-rust?

Firmware development for microcontrollers. Real-time control of sensors and actuators. IoT device programming and communication. Embedded systems prototyping and development. Safety-critical and low-level hardware software

What are the strengths of Embedded-rust?

Safe low-level programming with performance close to C/C++. Reduced risk of memory corruption and undefined behavior. Growing ecosystem for embedded hardware support. Concurrency and parallelism safety built into the language. Active community and modern tooling

What are the limitations of Embedded-rust?

Learning curve for ownership, lifetimes, and concurrency models. Limited ecosystem compared to C/C++ in some niche hardware. Compile times can be longer than C/C++. Tooling for debugging embedded Rust is still maturing. Some microcontroller support requires nightly Rust features

How can I practice Embedded-rust typing speed?

CodeSpeedTest offers 3+ real Embedded-rust code examples for typing practice. You can measure your WPM, track accuracy, and improve your coding speed with guided exercises.

Learn Other Programming Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypherGremlinPartiqlHaskellElixirFsharpView all languages →
CodeSpeedTest

Improve your coding speed, code accuracy, and programming syntax WPM with practice sessions across 500+ programming languages.

Quick Links

HomeAboutFeaturesGetting StartedLanguages

Legal & Support

Pro ⚡ PricingContactPrivacy PolicyTerms of Service

Connect

CodeSpeedTest on GitHubCodeSpeedTest on TwitterEmail CodeSpeedTest

© 2026 CodeSpeedTest. All rights reserved.