6.6 KiB
0x09 DHT11 Rust Driver
This repository contains a Bare-Metal Rust driver for the DHT11 Temperature and Humidity Sensor on the RP2350 (and RP2040) microcontrollers, implemented strictly using a GPIO pin and a hardware timer (no specialized hardware peripheral like PIO or PWM).
It includes:
- A demo (
src/main.rs) that continuously reads the sensor every 2 seconds and outputs the results over UART. - A reusable library module (
src/dht11.rs) providing a hardware-agnosticdht11_libcontaining the pure-logic checksum validation, data parsing, and string formatting routines. - Board initialization logic (
src/board.rs).
🚀 Getting Started from Scratch
If you're starting with a fresh machine, follow these exact steps to install the toolchain, build the code, and flash it to your microcontroller.
1. Install Rust
First, install rustup (the Rust toolchain installer) if you haven't already:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
Note: Restart your terminal or run source $HOME/.cargo/env after this finishes.
Ensure your Rust compiler is up to date:
rustup update
2. Install the Target Architecture
This project is configured for the RP2350 (ARM Cortex-M33). We need to install the cross-compilation target for it:
rustup target add thumbv8m.main-none-eabihf
(If you were targeting the RP2040, you would use thumbv6m-none-eabi instead).
3. Install Build Tools
You will need a few extra tools to help link and format the firmware for the RP-series chips.
Install flip-link (adds zero-cost stack overflow protection):
cargo install flip-link
Install picotool (used by cargo run to flash the chip):
- macOS:
brew install picotool - Linux/Windows: Follow the official Raspberry Pi documentation to install
picotoolor build it from source.
4. Building the Code
To compile the code for the microcontroller, simply run:
cargo build
To build a highly optimized release version (smaller and faster):
cargo build --release
5. Flashing to the Microcontroller
This project is pre-configured in .cargo/config.toml to use picotool as the custom runner.
To flash the code:
- Hold down the BOOTSEL button on your RP2350 board.
- Plug it into your computer via USB (or press the RUN/RESET button while holding BOOTSEL).
- Run the following command:
cargo run --release
cargo will compile the code and automatically use picotool to upload the .elf file directly to your board and start executing it!
6. Testing on the Host
Because the DHT11 data parsing, checksum validation, and string formatting logic is separated into a reusable math library without touching hardware registers, you can run the unit tests natively on your computer!
However, because this project sets a default bare-metal target (thumbv8m.main-none-eabihf) in .cargo/config.toml, running a plain cargo test will fail because the standard library doesn't exist on the microcontroller. You must explicitly tell Cargo to compile the tests for your host computer's processor architecture:
Mac (Apple Silicon):
cargo test --lib --target aarch64-apple-darwin
Linux (Intel/AMD 64-bit):
cargo test --lib --target x86_64-unknown-linux-gnu
Windows (64-bit):
cargo test --lib --target x86_64-pc-windows-msvc
🧠 Code Walkthrough
This section explains exactly how the code works, where the entry point is, and traces the flow of execution as if you were stepping through it line-by-line.
1. The Entry Point (src/main.rs)
Unlike a standard computer program, bare-metal microcontrollers do not have an operating system to call main(). Instead, we use the #[entry] macro from the HAL (Hardware Abstraction Layer) to define the very first function that runs after the chip boots up.
main() -> !: This is the absolute start of our code. It takes ownership of all the hardware peripherals (hal::pac::Peripherals::take().unwrap()) and immediately passes them intoboard::run(...). The-> !means this function never returns (because embedded devices run in an infinite loop).
2. Board Initialization (src/board.rs)
Once execution enters board.rs, we initialize the system clocks, pins, UART (for logging), SysTick (for delays), and a hardware timer (for microsecond precision measurement).
run(...): The master setup function. Calls the helper initialization functions below, prints an initialization message over UART, and enters the infinite polling loop.poll_sensor(...): Called repeatedly in the main loop. It invokes the read sequence, formats the result, writes it to UART, and blocks for 2 seconds (the DHT11's minimum polling interval).read_sensor(...): The high-level function for a single DHT11 read. It delegates toacquire_data()to handle the timing protocol, and then uses thedht11_libto parse the resulting 5-byte array into temperature and humidity.acquire_data(...): Executes the strict protocol: pulls the pin low for 18ms (send_start_signal()), waits for the sensor's acknowledgment (wait_response()), and reads 40 bits into an array (read_40_bits()).measure_bit_duration(...): Crucial for decoding the data. It waits for the sensor to pull the pin high, takes a timestamp, waits for it to pull low, takes another timestamp, and returns the duration.read_bit(...): Takes the measured pulse duration and calls the hardware-agnosticaccumulate_bit()function in thedht11_libto pack the 1 or 0 into the byte array.gpio_drive(...)&gpio_release(...): Manually flips theGPIO 4pin direction (output/input) via theSIO(Single-Cycle IO) registers to support the bidirectional 1-wire protocol.
3. The Reusable DHT11 Library (src/dht11.rs)
Because manipulating bits across byte boundaries and formatting floats without std::fmt can be error-prone, this module handles all pure-logic data manipulation.
accumulate_bit(...): Shifts the current byte left and inserts a1if the measured pulse duration exceeds the 40-microsecond threshold.validate_checksum(...): Adds the first four bytes (humidity int, humidity frac, temp int, temp frac) and ensures the lowest 8 bits match the fifth byte (the checksum).parse_humidity(...)&parse_temperature(...): Converts the specific byte pairs into standard floating-point numbers.format_reading(...)&format_error(...): Efficiently constructs the final ASCII string without allocating memory, allowing theboard.rscode to pipe the raw bytes directly to UART.