Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 14

HAL Crate: Peripheral Access Explained

Recommended resources

Welcome back! In our last lesson, you successfully set up and built your first embedded Rust project. While you now have a valid program for a microcontroller, it doesn't do anything yet because it has no way to interact with the hardware world. This lesson bridges that critical gap.

We are going to explore the cornerstone of hardware interaction in embedded Rust: the Hardware Abstraction Layer, or HAL. Your goal is to master embedded Rust, and understanding how HALs provide a safe, high-level, and portable way to control peripherals is fundamental to that goal. We will unpack the layers of abstraction involved and see how Rust's powerful type system is leveraged to prevent common hardware-related bugs at compile time.

From Registers to Abstractions

At the lowest level, controlling a microcontroller involves reading from and writing to specific memory addresses known as memory-mapped registers. Each bit in these registers might control a feature of a peripheral, like turning on a GPIO pin, setting a timer frequency, or configuring a serial port.

Working directly with registers is tedious and error-prone. You'd need the microcontroller's thousand-page reference manual by your side at all times, and a single incorrect bit flip could lead to unexpected behavior. This is where the embedded Rust ecosystem provides layers of abstraction to make development safer and more productive.

The Embedded Rust Book outlines these layers. Let's get an overview of the hierarchy.

Memory-mapped Registers - The Embedded Rust Book

This section introduces the different kinds of crates used to interact with hardware, establishing the context for where HALs fit in.

Please read the entire section, starting from the introduction. As you read, pay close attention to the distinct roles of the four types of crates described: Micro-architecture, Peripheral Access Crate (PAC), HAL Crate, and Board Crate.

As you just read, these crates form a stack, with each layer building upon the one below it.

This diagram illustrates the levels of abstraction, from the lowest-level PAC that directly maps to hardware registers, up to the highest-level Board Crate tailored for a specific development board.

Let's briefly define the two most important layers for our discussion:

  • Peripheral Access Crate (PAC): This is the foundation. A PAC is an auto-generated crate that provides a direct, one-to-one mapping of the microcontroller's memory-mapped registers. It is often considered unsafe to use directly because it doesn't prevent you from writing invalid configurations. It's the Rust equivalent of C header files provided by a chip vendor.
  • Hardware Abstraction Layer (HAL) Crate: This is our focus. A HAL is built on top of a PAC. Its purpose is to provide a safe, ergonomic, and high-level API for controlling peripherals. Instead of manually setting bits in a register, you call methods on objects that represent the hardware, like led_pin.set_high() or serial.write_byte(b'X').

The Role and Design of a HAL

A HAL's primary job is to abstract away the messy details of register manipulation. But a well-designed HAL in Rust does much more; it uses the language's features to enforce correct hardware usage. The following video provides an excellent summary.

Blinking an LED: Embedded Rust ecosystem explored

The video introduces the HAL as a higher-level, safer alternative to working directly with a PAC.

Watch the segment from "enter the hardware abstraction layer". Notice how the narrator frames the HAL not just as a convenience, but as a guide to properly use the hardware.

Standardization through embedded-hal

A key component of the ecosystem is the embedded-hal crate. It doesn't contain any code for a specific chip. Instead, it defines a set of standard traits for common peripherals. Traits, as you'll recall from our earlier modules, define shared behavior.

Introduction to embedded Rust

This blog post clearly explains the relationship between embedded-hal, HAL implementation crates, and PACs.

Please read the sections "Rust embedded working group" and "HAL implementations". Focus on how embedded-hal enables platform-agnostic code.

By having different HAL crates (e.g., stm32f4xx-hal, nrf52833-hal) implement the same traits from embedded-hal (like OutputPin for GPIOs or i2c::Write for I2C communication), you can write drivers for external components (like sensors) that are portable. A driver written against the embedded-hal traits will work with any microcontroller that has a compliant HAL.

This is a powerful concept that distinguishes embedded Rust from traditional C development, where porting a driver often means significant rewrites.

Safety Through the Type System: The "Secret Sauce"

Here is where embedded Rust truly shines. HALs use Rust's ownership and type system to represent the state of peripherals, preventing entire classes of bugs at compile time. This is often called a "typestate" pattern.

This next video segment is crucial. It explains how a HAL ensures you can't, for example, write to a pin that hasn't been configured as an output.

Blinking an LED: Embedded Rust ecosystem explored

This clip demonstrates how Rust's ownership and type system are used by a HAL to create compile-time guarantees about hardware state.

First, watch the practical demonstration of using a HAL to configure a GPIO pin from this segment. Then, watch the detailed explanation of the underlying safety mechanisms from this follow-up.

Let's break down the key ideas from that video:

  1. Ownership of Peripherals: The HAL requires you to "take" the peripherals singleton. Once you create a high-level representation of a peripheral (like GPIO Port A), you consume the underlying raw PAC struct. The borrow checker then prevents you from creating a second, conflicting instance. This ensures a single source of truth for each piece of hardware.

  2. State Transitions via Types: A pin is not just a "pin". It has a type that represents its current state, for example, PA5<Input<Floating>>. When you call a method like .into_push_pull_output(), you consume the pin in its old state and the method returns a new object with a new type, like PA5<Output<PushPull>>.

  3. Compile-Time Guarantees: The methods to control the pin (like set_high()) are only implemented for the output state type (PA5<Output<PushPull>>). If you try to call set_high() on a pin configured as an input, the program will not compile. In C, this would be a runtime error that is easy to make and can be difficult to debug. Rust HALs turn these runtime bugs into compile-time errors.


A HAL in Action: Code Example

Let's tie this all together by looking at a complete code example that uses a HAL. The following reading shows how to configure a serial port, which involves clocks, GPIO pins, and the UART peripheral itself.

Memory-mapped Registers - The Embedded Rust Book

This section provides a complete, annotated code example demonstrating how various HAL components work together to configure a peripheral.

Read the section "Using a HAL crate" for the conceptual explanation, and then carefully study the code block that follows, down to the end of the main function. As you read the code, identify the following patterns we've discussed: Taking ownership of the peripheral singleton (hal::Peripherals::take()). Consuming a raw PAC struct to create a higher-level object (.constrain()). Splitting a peripheral port into individual, owned pins (.split()). Converting a pin into a new state (.into_af_push_pull()). A peripheral constructor (Serial::uart0) that requires objects in their correctly configured states (clocks, configured pins) as arguments, enforcing dependencies.

This example perfectly illustrates how the HAL guides you through the correct sequence of operations. You cannot create a Serial object until you have first configured the system clocks and configured the necessary GPIO pins into their "alternate function" mode. The compiler enforces this dependency chain.


Conclusion

In this lesson, we've pulled back the curtain on how embedded Rust communicates with hardware. You've learned that simply having a project skeleton isn't enough; you need a way to safely and effectively command the microcontroller's peripherals.

Here are the key takeaways:

  • HALs abstract register access: They provide safe, high-level APIs for controlling hardware, freeing you from error-prone manual register manipulation.
  • The ecosystem is layered: Hardware interaction is typically structured with a low-level PAC providing direct register access and a higher-level HAL building upon it for safety and ergonomics.
  • embedded-hal enables portability: This crate defines a set of standard traits, allowing drivers and application logic to be written in a hardware-independent way.
  • Safety is enforced at compile time: Rust HALs uniquely leverage the type system and ownership model (typestates) to ensure peripherals are configured and used correctly, turning potential runtime bugs into compile-time errors.

You now have the theoretical foundation for peripheral access. In our next lesson, we will put this knowledge into practice. You will add a HAL crate to your blinky-app project and write the code to configure a GPIO pin as an output—the first concrete step toward making your LED blink.