rs-dht-pio/src/lib.rs

85 lines
2 KiB
Rust
Raw Normal View History

2023-09-08 21:09:15 +00:00
#![no_std]
use cortex_m::delay::Delay;
use rp2040_hal::gpio::AnyPin;
2023-09-09 20:22:30 +00:00
use rp2040_hal::pio::UninitStateMachine;
use rp2040_hal::pio::{PIOExt, StateMachineIndex};
mod dht;
use dht::DhtPio;
2023-09-08 21:09:15 +00:00
#[derive(Debug)]
pub enum DhtError {
/// Timeout during communication.
Timeout,
/// CRC mismatch.
2023-09-09 19:41:19 +00:00
CrcMismatch(u32, u32),
2023-09-08 21:13:58 +00:00
/// FIFO Read error
ReadError,
2023-09-08 21:09:15 +00:00
}
#[derive(Debug)]
pub struct DhtResult {
pub temperature: f32,
pub humidity: f32,
}
2023-09-09 20:22:30 +00:00
pub struct Dht22<P: PIOExt, STI: StateMachineIndex> {
dht: DhtPio<P, STI>,
2023-09-08 21:09:15 +00:00
}
2023-09-09 20:22:30 +00:00
impl<P: PIOExt, STI: StateMachineIndex> Dht22<P, STI> {
2023-09-08 21:09:15 +00:00
pub fn new<I: AnyPin<Function = P::PinFunction>>(
2023-09-09 20:22:30 +00:00
pio: rp2040_hal::pio::PIO<P>,
2023-09-08 21:09:15 +00:00
sm: UninitStateMachine<(P, STI)>,
dht_pin: I,
) -> Self {
Self {
2023-09-09 20:22:30 +00:00
dht: DhtPio::new(pio, sm, dht_pin),
2023-09-08 21:09:15 +00:00
}
}
2023-09-09 20:22:30 +00:00
pub fn read(&mut self, delay: &mut Delay) -> Result<DhtResult, DhtError> {
2023-10-10 06:33:04 +00:00
let (raw_temp, raw_hum) = self.dht.read_data(delay)?;
let mut final_t: f32 = (raw_temp & 0x7FFF) as f32;
2023-09-08 21:09:15 +00:00
2023-10-10 06:33:04 +00:00
if (raw_temp & 0x8000) > 0 {
final_t *= -1.0;
2023-09-08 21:09:15 +00:00
}
2023-09-09 20:22:30 +00:00
Ok(DhtResult {
2023-10-10 06:33:04 +00:00
temperature: final_t / 10.0,
humidity: raw_hum as f32 / 10.0,
2023-09-09 20:22:30 +00:00
})
}
}
pub struct Dht11<P: PIOExt, STI: StateMachineIndex> {
dht: DhtPio<P, STI>,
}
impl<P: PIOExt, STI: StateMachineIndex> Dht11<P, STI> {
pub fn new<I: AnyPin<Function = P::PinFunction>>(
pio: rp2040_hal::pio::PIO<P>,
sm: UninitStateMachine<(P, STI)>,
dht_pin: I,
) -> Self {
Self {
dht: DhtPio::new(pio, sm, dht_pin),
2023-09-08 21:09:15 +00:00
}
2023-09-09 20:22:30 +00:00
}
2023-09-08 21:09:15 +00:00
2023-09-09 20:22:30 +00:00
pub fn read(&mut self, delay: &mut Delay) -> Result<DhtResult, DhtError> {
let (t, h) = self.dht.read_data(delay)?;
2023-10-10 06:33:04 +00:00
let mut final_t: f32 = ((t & 0x7FFF) >> 8) as f32;
2023-09-09 19:41:19 +00:00
2023-09-09 20:22:30 +00:00
if (t & 0x8000) > 0 {
2023-10-10 06:33:04 +00:00
final_t *= -1.0;
2023-09-09 19:41:19 +00:00
}
2023-09-08 21:09:15 +00:00
Ok(DhtResult {
2023-10-10 06:33:04 +00:00
temperature: final_t,
2023-09-09 20:22:30 +00:00
humidity: (h >> 8) as f32,
2023-09-08 21:09:15 +00:00
})
}
}