Minimal Application

First, we build a minimal application and setup our project for this. We start with a new Rust project. The Cargo.toml should look like this:

[package]
name = "embedded_world"
version = "0.1.0"
edition = "2021"

[dependencies]
cortex-m = "=0.6.7"
cortex-m-rt = "=0.7.1"
nrf52840-hal = "0.14.0"

Hence, crate has the following dependencies:

  • cortex-m crate provides an API to talk with the Cortex-M processor.
  • cortex-m-rt is a runtime crate, allowing us to write an application.
  • nrf52840-hal is a hardware-abstraction layer (HAL) of the board we use (Board Support Package, BSP).

As we are writing an application, we also write a main.rs:

#![no_std]
#![no_main]

use core::fmt::Write;
use hal::{gpio, uarte, uarte::Uarte};
use nrf52840_hal as hal;

#[cortex_m_rt::entry]
fn main() -> ! {
    let mut core = cortex_m::peripheral::Peripherals::take().unwrap();
    core.DWT.enable_cycle_counter();

    let p = hal::pac::Peripherals::take().unwrap();

    let (uart0, cdc_pins) = {
        let p0 = gpio::p0::Parts::new(p.P0);
        (
            p.UARTE0,
            uarte::Pins {
                txd: p0.p0_06.into_push_pull_output(gpio::Level::High).degrade(),
                rxd: p0.p0_08.into_floating_input().degrade(),
                cts: None,
                rts: None,
            },
        )
    };
    let mut uarte = Uarte::new(
        uart0,
        cdc_pins,
        uarte::Parity::EXCLUDED,
        uarte::Baudrate::BAUD115200,
    );

    write!(uarte, "Hello Embedded World\r\n").unwrap();

    loop {
        cortex_m::asm::wfi();
    }
}

#[panic_handler] // panicking behavior
fn panic(_: &core::panic::PanicInfo) -> ! {
    loop {
        cortex_m::asm::bkpt();
    }
}