Learn EMBEDDED-RUST with Real Code Examples
Updated Nov 27, 2025
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.
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.
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.