mirror of
https://github.com/mytechnotalent/Embedded-Hacking.git
synced 2026-05-26 17:28:25 +02:00
Add 0x09_dht11_rust: DHT11 temperature/humidity sensor driver
This commit is contained in:
@@ -0,0 +1,385 @@
|
||||
//! @file board.rs
|
||||
//! @brief Board-level HAL helpers for the DHT11 driver
|
||||
//! @author Kevin Thomas
|
||||
//! @date 2025
|
||||
//!
|
||||
//! MIT License
|
||||
//!
|
||||
//! Copyright (c) 2025 Kevin Thomas
|
||||
//!
|
||||
//! Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
//! of this software and associated documentation files (the "Software"), to deal
|
||||
//! in the Software without restriction, including without limitation the rights
|
||||
//! to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
//! copies of the Software, and to permit persons to whom the Software is
|
||||
//! furnished to do so, subject to the following conditions:
|
||||
//!
|
||||
//! The above copyright notice and this permission notice shall be included in
|
||||
//! all copies or substantial portions of the Software.
|
||||
//!
|
||||
//! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
//! IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
//! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
//! AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
//! LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
//! OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
//! SOFTWARE.
|
||||
|
||||
// DHT11 pure-logic functions (checksum, parsing, formatting)
|
||||
use crate::dht11;
|
||||
// Rate extension trait for .Hz() baud rate construction
|
||||
use fugit::RateExtU32;
|
||||
// Clock trait for accessing system clock frequency
|
||||
use hal::Clock;
|
||||
// GPIO pin types and function selectors
|
||||
use hal::gpio::{FunctionNull, FunctionUart, Pin, PullDown, PullNone};
|
||||
// UART configuration and peripheral types
|
||||
use hal::uart::{DataBits, Enabled, StopBits, UartConfig, UartPeripheral};
|
||||
|
||||
// Alias our HAL crate
|
||||
#[cfg(rp2350)]
|
||||
use rp235x_hal as hal;
|
||||
#[cfg(rp2040)]
|
||||
use rp2040_hal as hal;
|
||||
|
||||
// Timer device type for the HAL timer peripheral
|
||||
#[cfg(rp2350)]
|
||||
pub(crate) type HalTimer = hal::Timer<hal::timer::CopyableTimer0>;
|
||||
// Timer type alias for RP2040 (non-generic)
|
||||
#[cfg(rp2040)]
|
||||
pub(crate) type HalTimer = hal::Timer;
|
||||
|
||||
/// External crystal frequency in Hz (12 MHz).
|
||||
pub(crate) const XTAL_FREQ_HZ: u32 = 12_000_000u32;
|
||||
|
||||
/// UART baud rate in bits per second.
|
||||
pub(crate) const UART_BAUD: u32 = 115_200;
|
||||
|
||||
/// GPIO pin number connected to the DHT11 data line.
|
||||
pub(crate) const DHT11_GPIO: u8 = 4;
|
||||
|
||||
/// Polling interval in milliseconds (DHT11 minimum is 2 seconds).
|
||||
pub(crate) const POLL_MS: u32 = 2_000;
|
||||
|
||||
/// Type alias for the configured TX pin (GPIO 0, UART function, no pull).
|
||||
pub(crate) type TxPin = Pin<hal::gpio::bank0::Gpio0, FunctionUart, PullNone>;
|
||||
|
||||
/// Type alias for the configured RX pin (GPIO 1, UART function, no pull).
|
||||
pub(crate) type RxPin = Pin<hal::gpio::bank0::Gpio1, FunctionUart, PullNone>;
|
||||
|
||||
/// Type alias for the default TX pin state from `Pins::new()`.
|
||||
pub(crate) type TxPinDefault = Pin<hal::gpio::bank0::Gpio0, FunctionNull, PullDown>;
|
||||
|
||||
/// Type alias for the default RX pin state from `Pins::new()`.
|
||||
pub(crate) type RxPinDefault = Pin<hal::gpio::bank0::Gpio1, FunctionNull, PullDown>;
|
||||
|
||||
/// Type alias for the fully-enabled UART0 peripheral with TX/RX pins.
|
||||
pub(crate) type EnabledUart = UartPeripheral<Enabled, hal::pac::UART0, (TxPin, RxPin)>;
|
||||
|
||||
/// Initialise system clocks and PLLs from the external 12 MHz crystal.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `xosc` - XOSC peripheral singleton.
|
||||
/// * `clocks` - CLOCKS peripheral singleton.
|
||||
/// * `pll_sys` - PLL_SYS peripheral singleton.
|
||||
/// * `pll_usb` - PLL_USB peripheral singleton.
|
||||
/// * `resets` - Mutable reference to the RESETS peripheral.
|
||||
/// * `watchdog` - Mutable reference to the watchdog timer.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Configured clocks manager.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if clock initialisation fails.
|
||||
pub(crate) fn init_clocks(
|
||||
xosc: hal::pac::XOSC,
|
||||
clocks: hal::pac::CLOCKS,
|
||||
pll_sys: hal::pac::PLL_SYS,
|
||||
pll_usb: hal::pac::PLL_USB,
|
||||
resets: &mut hal::pac::RESETS,
|
||||
watchdog: &mut hal::Watchdog,
|
||||
) -> hal::clocks::ClocksManager {
|
||||
hal::clocks::init_clocks_and_plls(
|
||||
XTAL_FREQ_HZ, xosc, clocks, pll_sys, pll_usb, resets, watchdog,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Unlock the GPIO bank and return the pin set.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `io_bank0` - IO_BANK0 peripheral singleton.
|
||||
/// * `pads_bank0` - PADS_BANK0 peripheral singleton.
|
||||
/// * `sio` - SIO peripheral singleton.
|
||||
/// * `resets` - Mutable reference to the RESETS peripheral.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// GPIO pin set for the entire bank.
|
||||
pub(crate) fn init_pins(
|
||||
io_bank0: hal::pac::IO_BANK0,
|
||||
pads_bank0: hal::pac::PADS_BANK0,
|
||||
sio: hal::pac::SIO,
|
||||
resets: &mut hal::pac::RESETS,
|
||||
) -> hal::gpio::Pins {
|
||||
let sio = hal::Sio::new(sio);
|
||||
hal::gpio::Pins::new(io_bank0, pads_bank0, sio.gpio_bank0, resets)
|
||||
}
|
||||
|
||||
/// Initialise UART0 for serial output (stdio equivalent).
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `uart0` - PAC UART0 peripheral singleton.
|
||||
/// * `tx_pin` - GPIO pin to use as UART0 TX (GPIO 0).
|
||||
/// * `rx_pin` - GPIO pin to use as UART0 RX (GPIO 1).
|
||||
/// * `resets` - Mutable reference to the RESETS peripheral.
|
||||
/// * `clocks` - Reference to the initialised clock configuration.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Enabled UART0 peripheral ready for blocking writes.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if the HAL cannot achieve the requested baud rate.
|
||||
pub(crate) fn init_uart(
|
||||
uart0: hal::pac::UART0,
|
||||
tx_pin: TxPinDefault,
|
||||
rx_pin: RxPinDefault,
|
||||
resets: &mut hal::pac::RESETS,
|
||||
clocks: &hal::clocks::ClocksManager,
|
||||
) -> EnabledUart {
|
||||
let pins = (
|
||||
tx_pin.reconfigure::<FunctionUart, PullNone>(),
|
||||
rx_pin.reconfigure::<FunctionUart, PullNone>(),
|
||||
);
|
||||
let cfg = UartConfig::new(UART_BAUD.Hz(), DataBits::Eight, None, StopBits::One);
|
||||
UartPeripheral::new(uart0, pins, resets)
|
||||
.enable(cfg, clocks.peripheral_clock.freq())
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Create a blocking delay timer from the ARM SysTick peripheral.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `clocks` - Reference to the initialised clock configuration.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Blocking delay provider.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if the cortex-m core peripherals have already been taken.
|
||||
pub(crate) fn init_delay(clocks: &hal::clocks::ClocksManager) -> cortex_m::delay::Delay {
|
||||
let core = cortex_m::Peripherals::take().unwrap();
|
||||
cortex_m::delay::Delay::new(core.SYST, clocks.system_clock.freq().to_Hz())
|
||||
}
|
||||
|
||||
/// Drive the DHT11 data pin to a given level (enables output).
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `high` - `true` to drive HIGH, `false` to drive LOW.
|
||||
fn gpio_drive(high: bool) {
|
||||
unsafe {
|
||||
let sio = &*hal::pac::SIO::PTR;
|
||||
if high {
|
||||
sio.gpio_out_set().write(|w| w.bits(1u32 << DHT11_GPIO));
|
||||
} else {
|
||||
sio.gpio_out_clr().write(|w| w.bits(1u32 << DHT11_GPIO));
|
||||
}
|
||||
sio.gpio_oe_set().write(|w| w.bits(1u32 << DHT11_GPIO));
|
||||
}
|
||||
}
|
||||
|
||||
/// Release the DHT11 data pin back to input mode (disable output driver).
|
||||
fn gpio_release() {
|
||||
unsafe {
|
||||
let sio = &*hal::pac::SIO::PTR;
|
||||
sio.gpio_oe_clr().write(|w| w.bits(1u32 << DHT11_GPIO));
|
||||
}
|
||||
}
|
||||
|
||||
/// Read the current logic level of the DHT11 data pin.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// `true` if the pin reads HIGH, `false` if LOW.
|
||||
fn gpio_read() -> bool {
|
||||
unsafe { (*hal::pac::SIO::PTR).gpio_in().read().bits() & (1u32 << DHT11_GPIO) != 0 }
|
||||
}
|
||||
|
||||
/// Read the free-running microsecond timer (lower 32 bits).
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `timer` - Reference to the HAL timer peripheral.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Current timer value in microseconds (wrapping at 2^32).
|
||||
fn time_us_32(timer: &HalTimer) -> u32 {
|
||||
timer.get_counter().ticks() as u32
|
||||
}
|
||||
|
||||
/// Send the DHT11 start signal on the data pin.
|
||||
///
|
||||
/// Drives the pin LOW for 18 ms then HIGH for 40 us before switching
|
||||
/// the pin to input mode to listen for the sensor response.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `delay` - Mutable reference to the blocking delay provider.
|
||||
fn send_start_signal(delay: &mut cortex_m::delay::Delay) {
|
||||
gpio_drive(false);
|
||||
delay.delay_ms(18);
|
||||
gpio_drive(true);
|
||||
delay.delay_us(40);
|
||||
gpio_release();
|
||||
}
|
||||
|
||||
/// Spin until the pin leaves the given logic level, or time out.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `level` - Logic level to wait through (`true` = HIGH, `false` = LOW).
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// `true` once the level changed, `false` on timeout.
|
||||
fn wait_for_level(level: bool) -> bool {
|
||||
let mut timeout: u32 = dht11::LEVEL_WAIT_TIMEOUT;
|
||||
while gpio_read() == level {
|
||||
timeout -= 1;
|
||||
if timeout == 0 {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Wait for the DHT11 response after the start signal.
|
||||
///
|
||||
/// The sensor pulls LOW then HIGH then LOW again; each transition
|
||||
/// is awaited with a timeout.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// `true` if the full response was received, `false` on timeout.
|
||||
fn wait_response() -> bool {
|
||||
wait_for_level(true) && wait_for_level(false) && wait_for_level(true)
|
||||
}
|
||||
|
||||
/// Read a single bit from the DHT11 data stream.
|
||||
///
|
||||
/// Waits for the low-period to end, measures the high-period duration,
|
||||
/// and accumulates the result into the data array via
|
||||
/// [`dht11::accumulate_bit`].
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `data` - 5-byte array accumulating the received bits.
|
||||
/// * `i` - Bit index (0–39).
|
||||
/// * `timer` - Reference to the HAL timer for microsecond measurement.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// `true` on success, `false` on timeout.
|
||||
fn read_bit(data: &mut [u8; 5], i: usize, timer: &HalTimer) -> bool {
|
||||
if !wait_for_level(false) {
|
||||
return false;
|
||||
}
|
||||
let start = time_us_32(timer);
|
||||
if !wait_for_level(true) {
|
||||
return false;
|
||||
}
|
||||
let duration = time_us_32(timer).wrapping_sub(start);
|
||||
dht11::accumulate_bit(data, i, duration);
|
||||
true
|
||||
}
|
||||
|
||||
/// Read all 40 data bits from the DHT11.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `data` - 5-byte array filled with the received data.
|
||||
/// * `timer` - Reference to the HAL timer for microsecond measurement.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// `true` if all 40 bits were read, `false` on timeout.
|
||||
fn read_40_bits(data: &mut [u8; 5], timer: &HalTimer) -> bool {
|
||||
for i in 0..40 {
|
||||
if !read_bit(data, i, timer) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Execute the full DHT11 read protocol.
|
||||
///
|
||||
/// Sends the start signal, waits for the sensor response, reads 40 bits
|
||||
/// of data, validates the checksum, and parses humidity and temperature.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `timer` - Reference to the HAL timer for microsecond measurement.
|
||||
/// * `delay` - Mutable reference to the blocking delay provider.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// `Some((humidity, temperature))` on success, `None` on failure.
|
||||
pub(crate) fn read_sensor(
|
||||
timer: &HalTimer,
|
||||
delay: &mut cortex_m::delay::Delay,
|
||||
) -> Option<(f32, f32)> {
|
||||
let mut data = [0u8; 5];
|
||||
send_start_signal(delay);
|
||||
if !wait_response() {
|
||||
return None;
|
||||
}
|
||||
if !read_40_bits(&mut data, timer) {
|
||||
return None;
|
||||
}
|
||||
if !dht11::validate_checksum(&data) {
|
||||
return None;
|
||||
}
|
||||
Some((dht11::parse_humidity(&data), dht11::parse_temperature(&data)))
|
||||
}
|
||||
|
||||
/// Read the sensor, format the result, write it over UART, and wait.
|
||||
///
|
||||
/// On a successful read, prints humidity and temperature; on failure,
|
||||
/// prints a wiring-check message. Always waits [`POLL_MS`] before
|
||||
/// returning to respect the DHT11 minimum polling interval.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `uart` - Reference to the enabled UART peripheral for serial output.
|
||||
/// * `timer` - Reference to the HAL timer for microsecond measurement.
|
||||
/// * `delay` - Mutable reference to the blocking delay provider.
|
||||
pub(crate) fn poll_sensor(
|
||||
uart: &EnabledUart,
|
||||
timer: &HalTimer,
|
||||
delay: &mut cortex_m::delay::Delay,
|
||||
) {
|
||||
let mut buf = [0u8; 64];
|
||||
let n = match read_sensor(timer, delay) {
|
||||
Some((h, t)) => dht11::format_reading(&mut buf, h, t),
|
||||
None => dht11::format_error(&mut buf, DHT11_GPIO),
|
||||
};
|
||||
buf[n] = b'\r';
|
||||
buf[n + 1] = b'\n';
|
||||
uart.write_full_blocking(&buf[..n + 2]);
|
||||
delay.delay_ms(POLL_MS);
|
||||
}
|
||||
|
||||
// End of file
|
||||
@@ -0,0 +1,343 @@
|
||||
//! @file dht11.rs
|
||||
//! @brief Implementation of DHT11 temperature and humidity sensor driver
|
||||
//! @author Kevin Thomas
|
||||
//! @date 2025
|
||||
//!
|
||||
//! MIT License
|
||||
//!
|
||||
//! Copyright (c) 2025 Kevin Thomas
|
||||
//!
|
||||
//! Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
//! of this software and associated documentation files (the "Software"), to deal
|
||||
//! in the Software without restriction, including without limitation the rights
|
||||
//! to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
//! copies of the Software, and to permit persons to whom the Software is
|
||||
//! furnished to do so, subject to the following conditions:
|
||||
//!
|
||||
//! The above copyright notice and this permission notice shall be included in
|
||||
//! all copies or substantial portions of the Software.
|
||||
//!
|
||||
//! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
//! IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
//! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
//! AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
//! LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
//! OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
//! SOFTWARE.
|
||||
|
||||
/// Bit-duration threshold in microseconds.
|
||||
///
|
||||
/// If the high pulse is longer than this value, the bit is a 1; otherwise 0.
|
||||
pub const BIT_THRESHOLD_US: u32 = 40;
|
||||
|
||||
/// Timeout in spin-loop iterations for waiting on a pin level change.
|
||||
pub const LEVEL_WAIT_TIMEOUT: u32 = 10_000;
|
||||
|
||||
/// Accumulate a single received bit into the 5-byte data array.
|
||||
///
|
||||
/// Shifts `data[byte_index]` left by one and sets the LSB to 1 if the
|
||||
/// measured high-pulse `duration_us` exceeds [`BIT_THRESHOLD_US`].
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `data` - 5-byte array accumulating the received bits.
|
||||
/// * `bit_index` - Bit index (0..39).
|
||||
/// * `duration_us` - Measured duration of the high pulse in microseconds.
|
||||
pub fn accumulate_bit(data: &mut [u8; 5], bit_index: usize, duration_us: u32) {
|
||||
let byte = bit_index / 8;
|
||||
data[byte] <<= 1;
|
||||
if duration_us > BIT_THRESHOLD_US {
|
||||
data[byte] |= 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// Verify the DHT11 checksum byte.
|
||||
///
|
||||
/// The checksum (byte 4) must equal the lower 8 bits of the sum of
|
||||
/// bytes 0 through 3.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `data` - 5-byte received data (bytes 0–3 plus checksum in byte 4).
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// `true` if the checksum matches, `false` otherwise.
|
||||
pub fn validate_checksum(data: &[u8; 5]) -> bool {
|
||||
data[4] == (data[0].wrapping_add(data[1]).wrapping_add(data[2]).wrapping_add(data[3]))
|
||||
}
|
||||
|
||||
/// Parse humidity from the raw DHT11 data bytes.
|
||||
///
|
||||
/// Humidity is encoded as an integer part in byte 0 and a fractional
|
||||
/// part (tenths) in byte 1.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `data` - 5-byte received data.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Humidity as a percentage (e.g. 65.3 for 65.3%).
|
||||
pub fn parse_humidity(data: &[u8; 5]) -> f32 {
|
||||
data[0] as f32 + data[1] as f32 * 0.1
|
||||
}
|
||||
|
||||
/// Parse temperature from the raw DHT11 data bytes.
|
||||
///
|
||||
/// Temperature is encoded as an integer part in byte 2 and a fractional
|
||||
/// part (tenths) in byte 3.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `data` - 5-byte received data.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Temperature in degrees Celsius.
|
||||
pub fn parse_temperature(data: &[u8; 5]) -> f32 {
|
||||
data[2] as f32 + data[3] as f32 * 0.1
|
||||
}
|
||||
|
||||
/// Format a sensor reading as `"Humidity: XX.X% Temperature: XX.X C"`.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `buf` - Mutable byte slice (must be at least 40 bytes).
|
||||
/// * `humidity` - Humidity percentage.
|
||||
/// * `temperature` - Temperature in degrees Celsius.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Number of bytes written into the buffer.
|
||||
pub fn format_reading(buf: &mut [u8], humidity: f32, temperature: f32) -> usize {
|
||||
let mut pos = 0;
|
||||
let prefix = b"Humidity: ";
|
||||
buf[pos..pos + prefix.len()].copy_from_slice(prefix);
|
||||
pos += prefix.len();
|
||||
pos += format_f32_1(&mut buf[pos..], humidity);
|
||||
let mid = b"% Temperature: ";
|
||||
buf[pos..pos + mid.len()].copy_from_slice(mid);
|
||||
pos += mid.len();
|
||||
pos += format_f32_1(&mut buf[pos..], temperature);
|
||||
let suffix = b" C";
|
||||
buf[pos..pos + suffix.len()].copy_from_slice(suffix);
|
||||
pos += suffix.len();
|
||||
pos
|
||||
}
|
||||
|
||||
/// Format a failed-read error message.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `buf` - Mutable byte slice (must be at least 42 bytes).
|
||||
/// * `gpio` - GPIO pin number to include in the message.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Number of bytes written into the buffer.
|
||||
pub fn format_error(buf: &mut [u8], gpio: u8) -> usize {
|
||||
let mut pos = 0;
|
||||
let prefix = b"DHT11 read failed - check wiring on GPIO ";
|
||||
buf[pos..pos + prefix.len()].copy_from_slice(prefix);
|
||||
pos += prefix.len();
|
||||
pos += format_u8(&mut buf[pos..], gpio);
|
||||
pos
|
||||
}
|
||||
|
||||
/// Format a `u8` as decimal ASCII digits.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `buf` - Output buffer.
|
||||
/// * `val` - Value to format.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Number of bytes written.
|
||||
fn format_u8(buf: &mut [u8], val: u8) -> usize {
|
||||
if val >= 100 {
|
||||
buf[0] = b'0' + val / 100;
|
||||
buf[1] = b'0' + (val / 10) % 10;
|
||||
buf[2] = b'0' + val % 10;
|
||||
3
|
||||
} else if val >= 10 {
|
||||
buf[0] = b'0' + val / 10;
|
||||
buf[1] = b'0' + val % 10;
|
||||
2
|
||||
} else {
|
||||
buf[0] = b'0' + val;
|
||||
1
|
||||
}
|
||||
}
|
||||
|
||||
/// Format an `f32` with one decimal place (e.g. `"25.3"`).
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `buf` - Output buffer.
|
||||
/// * `val` - Value to format.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Number of bytes written.
|
||||
fn format_f32_1(buf: &mut [u8], val: f32) -> usize {
|
||||
let scaled = (val * 10.0) as u32;
|
||||
let integer = scaled / 10;
|
||||
let frac = (scaled % 10) as u8;
|
||||
let mut pos = 0;
|
||||
if integer >= 100 {
|
||||
buf[pos] = b'0' + (integer / 100) as u8;
|
||||
pos += 1;
|
||||
}
|
||||
if integer >= 10 {
|
||||
buf[pos] = b'0' + ((integer / 10) % 10) as u8;
|
||||
pos += 1;
|
||||
}
|
||||
buf[pos] = b'0' + (integer % 10) as u8;
|
||||
pos += 1;
|
||||
buf[pos] = b'.';
|
||||
pos += 1;
|
||||
buf[pos] = b'0' + frac;
|
||||
pos += 1;
|
||||
pos
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
// Import all parent module items
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn accumulate_bit_zero_short_pulse() {
|
||||
let mut data = [0u8; 5];
|
||||
accumulate_bit(&mut data, 0, 30);
|
||||
assert_eq!(data[0], 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accumulate_bit_one_long_pulse() {
|
||||
let mut data = [0u8; 5];
|
||||
accumulate_bit(&mut data, 0, 70);
|
||||
assert_eq!(data[0], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accumulate_bit_threshold_exact() {
|
||||
let mut data = [0u8; 5];
|
||||
accumulate_bit(&mut data, 0, BIT_THRESHOLD_US);
|
||||
assert_eq!(data[0], 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accumulate_bit_two_bits() {
|
||||
let mut data = [0u8; 5];
|
||||
accumulate_bit(&mut data, 0, 70);
|
||||
accumulate_bit(&mut data, 1, 30);
|
||||
assert_eq!(data[0], 0b10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accumulate_bit_crosses_byte() {
|
||||
let mut data = [0u8; 5];
|
||||
accumulate_bit(&mut data, 7, 70);
|
||||
accumulate_bit(&mut data, 8, 70);
|
||||
assert_eq!(data[0], 1);
|
||||
assert_eq!(data[1], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_checksum_valid() {
|
||||
let data = [0x28, 0x00, 0x1A, 0x00, 0x42];
|
||||
assert!(validate_checksum(&data));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_checksum_invalid() {
|
||||
let data = [0x28, 0x00, 0x1A, 0x00, 0xFF];
|
||||
assert!(!validate_checksum(&data));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_checksum_wraps() {
|
||||
let data = [0xFF, 0x01, 0x00, 0x00, 0x00];
|
||||
assert!(validate_checksum(&data));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_humidity_integer_only() {
|
||||
let data = [0x41, 0x00, 0x00, 0x00, 0x41];
|
||||
let h = parse_humidity(&data);
|
||||
assert!((h - 65.0).abs() < 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_humidity_with_fraction() {
|
||||
let data = [0x41, 0x03, 0x00, 0x00, 0x44];
|
||||
let h = parse_humidity(&data);
|
||||
assert!((h - 65.3).abs() < 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_temperature_integer_only() {
|
||||
let data = [0x00, 0x00, 0x19, 0x00, 0x19];
|
||||
let t = parse_temperature(&data);
|
||||
assert!((t - 25.0).abs() < 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_temperature_with_fraction() {
|
||||
let data = [0x00, 0x00, 0x19, 0x05, 0x1E];
|
||||
let t = parse_temperature(&data);
|
||||
assert!((t - 25.5).abs() < 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_reading_typical() {
|
||||
let mut buf = [0u8; 48];
|
||||
let n = format_reading(&mut buf, 65.0, 25.0);
|
||||
assert_eq!(&buf[..n], b"Humidity: 65.0% Temperature: 25.0 C");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_reading_with_fractions() {
|
||||
let mut buf = [0u8; 48];
|
||||
let n = format_reading(&mut buf, 65.3, 25.5);
|
||||
assert_eq!(&buf[..n], b"Humidity: 65.3% Temperature: 25.5 C");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_error_gpio4() {
|
||||
let mut buf = [0u8; 48];
|
||||
let n = format_error(&mut buf, 4);
|
||||
assert_eq!(&buf[..n], b"DHT11 read failed - check wiring on GPIO 4");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_error_gpio15() {
|
||||
let mut buf = [0u8; 48];
|
||||
let n = format_error(&mut buf, 15);
|
||||
assert_eq!(&buf[..n], b"DHT11 read failed - check wiring on GPIO 15");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_u8_single_digit() {
|
||||
let mut buf = [0u8; 4];
|
||||
let n = format_u8(&mut buf, 4);
|
||||
assert_eq!(&buf[..n], b"4");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_u8_two_digits() {
|
||||
let mut buf = [0u8; 4];
|
||||
let n = format_u8(&mut buf, 15);
|
||||
assert_eq!(&buf[..n], b"15");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_u8_three_digits() {
|
||||
let mut buf = [0u8; 4];
|
||||
let n = format_u8(&mut buf, 255);
|
||||
assert_eq!(&buf[..n], b"255");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
//! @file lib.rs
|
||||
//! @brief Library root for the DHT11 driver crate
|
||||
//! @author Kevin Thomas
|
||||
//! @date 2025
|
||||
|
||||
#![no_std]
|
||||
|
||||
// DHT11 driver module
|
||||
pub mod dht11;
|
||||
@@ -0,0 +1,120 @@
|
||||
//! @file main.rs
|
||||
//! @brief DHT11 temperature and humidity sensor demonstration
|
||||
//! @author Kevin Thomas
|
||||
//! @date 2025
|
||||
//!
|
||||
//! MIT License
|
||||
//!
|
||||
//! Copyright (c) 2025 Kevin Thomas
|
||||
//!
|
||||
//! Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
//! of this software and associated documentation files (the "Software"), to deal
|
||||
//! in the Software without restriction, including without limitation the rights
|
||||
//! to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
//! copies of the Software, and to permit persons to whom the Software is
|
||||
//! furnished to do so, subject to the following conditions:
|
||||
//!
|
||||
//! The above copyright notice and this permission notice shall be included in
|
||||
//! all copies or substantial portions of the Software.
|
||||
//!
|
||||
//! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
//! IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
//! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
//! AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
//! LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
//! OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
//! SOFTWARE.
|
||||
//!
|
||||
//! -----------------------------------------------------------------------------
|
||||
//!
|
||||
//! Demonstrates how to read temperature and humidity from a DHT11
|
||||
//! sensor using the dht11.rs driver. The sensor is polled every 2
|
||||
//! seconds (the minimum safe interval for the DHT11) and the results
|
||||
//! are printed over UART. A failed read is reported so wiring issues
|
||||
//! are visible.
|
||||
//!
|
||||
//! Wiring:
|
||||
//! GPIO4 -> DHT11 DATA pin (10 kohm pull-up to 3.3 V recommended)
|
||||
//! 3.3V -> DHT11 VCC
|
||||
//! GND -> DHT11 GND
|
||||
|
||||
#![no_std]
|
||||
#![no_main]
|
||||
|
||||
// Board-level helpers: constants, type aliases, and init functions
|
||||
mod board;
|
||||
// DHT11 driver module — suppress warnings for unused public API functions
|
||||
#[allow(dead_code)]
|
||||
mod dht11;
|
||||
|
||||
// Debugging output over RTT
|
||||
use defmt_rtt as _;
|
||||
// Panic handler for RISC-V targets
|
||||
#[cfg(target_arch = "riscv32")]
|
||||
use panic_halt as _;
|
||||
// Panic handler for ARM targets
|
||||
#[cfg(target_arch = "arm")]
|
||||
use panic_probe as _;
|
||||
|
||||
// HAL entry-point macro
|
||||
use hal::entry;
|
||||
|
||||
// Alias our HAL crate
|
||||
#[cfg(rp2350)]
|
||||
use rp235x_hal as hal;
|
||||
#[cfg(rp2040)]
|
||||
use rp2040_hal as hal;
|
||||
|
||||
// Second-stage boot loader for RP2040
|
||||
#[unsafe(link_section = ".boot2")]
|
||||
#[used]
|
||||
#[cfg(rp2040)]
|
||||
pub static BOOT2: [u8; 256] = rp2040_boot2::BOOT_LOADER_W25Q080;
|
||||
|
||||
// Boot metadata for the RP2350 Boot ROM
|
||||
#[unsafe(link_section = ".start_block")]
|
||||
#[used]
|
||||
#[cfg(rp2350)]
|
||||
pub static IMAGE_DEF: hal::block::ImageDef = hal::block::ImageDef::secure_exe();
|
||||
|
||||
/// Application entry point for the DHT11 sensor demo.
|
||||
///
|
||||
/// Initializes the DHT11 on GPIO4 and continuously reads temperature
|
||||
/// and humidity, printing results over UART every 2 seconds.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Does not return.
|
||||
#[entry]
|
||||
fn main() -> ! {
|
||||
let mut pac = hal::pac::Peripherals::take().unwrap();
|
||||
let clocks = board::init_clocks(
|
||||
pac.XOSC, pac.CLOCKS, pac.PLL_SYS, pac.PLL_USB, &mut pac.RESETS,
|
||||
&mut hal::Watchdog::new(pac.WATCHDOG),
|
||||
);
|
||||
let pins = board::init_pins(pac.IO_BANK0, pac.PADS_BANK0, pac.SIO, &mut pac.RESETS);
|
||||
let uart = board::init_uart(pac.UART0, pins.gpio0, pins.gpio1, &mut pac.RESETS, &clocks);
|
||||
let mut delay = board::init_delay(&clocks);
|
||||
#[cfg(rp2350)]
|
||||
let timer = hal::Timer::new_timer0(pac.TIMER0, &mut pac.RESETS, &clocks);
|
||||
#[cfg(rp2040)]
|
||||
let timer = hal::Timer::new(pac.TIMER, &mut pac.RESETS);
|
||||
let _dht_pin = pins.gpio4.into_pull_up_input();
|
||||
uart.write_full_blocking(b"DHT11 driver initialized on GPIO 4\r\n");
|
||||
loop {
|
||||
board::poll_sensor(&uart, &timer, &mut delay);
|
||||
}
|
||||
}
|
||||
|
||||
// Picotool binary info metadata
|
||||
#[unsafe(link_section = ".bi_entries")]
|
||||
#[used]
|
||||
pub static PICOTOOL_ENTRIES: [hal::binary_info::EntryAddr; 5] = [
|
||||
hal::binary_info::rp_cargo_bin_name!(),
|
||||
hal::binary_info::rp_cargo_version!(),
|
||||
hal::binary_info::rp_program_description!(c"DHT11 Sensor Demo"),
|
||||
hal::binary_info::rp_cargo_homepage_url!(),
|
||||
hal::binary_info::rp_program_build_attribute!(),
|
||||
];
|
||||
|
||||
// End of file
|
||||
Reference in New Issue
Block a user