1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
//! # DHT11/DHT22 sensor driver
//!
//! This library provides a platform-agnostic driver for the [DHT11 and DHT22](https://learn.adafruit.com/dht/overview) sensors.
//!
//! Use one of two functions [`dht11::Reading::read`] and [`dht22::Reading::read`] to get a reading.
//!
//! [`dht11::Reading::read`]: dht11/struct.Reading.html#method.read
//! [`dht22::Reading::read`]: dht22/struct.Reading.html#method.read
//!
//! ## Usage
//!
//! The only prerequisites are an embedded-hal implementation that provides:
//!
//! - [`Delay`]-implementing type, for example Cortex-M microcontrollers typically use the `SysTick`.
//! - [`InputOutputPin`]-implementing type, for example an `Output<OpenDrain>` from `stm32f0xx_hal`.
//!
//! When initializing the pin as an output, the state of the pin might depend on the specific chip
//! used. Some might pull the pin low by default causing the sensor to be confused when we actually
//! read it for the first time. The same thing happens when the sensor is polled too quickly in succession.
//! In both of those cases you will get a `DhtError::Timeout`.
//!
//! To avoid this, you can pull the pin high when initializing it and polling the sensor with an
//! interval of at least 500ms (determined experimentally). Some sources state a refresh rate of 1 or even 2 seconds.
//!
//! ## Example
//!
//! See the [stm32f042 example](https://github.com/michaelbeaumont/dht-sensor/blob/master/examples/stm32f042.rs) for a working example of
//! how to use the library.
//!
//! ```
//! #![no_std]
//! #![no_main]
//!
//! use crate::hal::{delay, gpio, prelude::*, stm32};
//! use cortex_m_rt::entry;
//! use cortex_m_semihosting::hprintln;
//! use panic_halt as _;
//! use stm32f0xx_hal as hal;
//!
//! use dht_sensor::*;
//!
//! #[entry]
//! fn main() -> ! {
//!     let mut p = stm32::Peripherals::take().unwrap();
//!     let cp = stm32::CorePeripherals::take().unwrap();
//!     let mut rcc = p.RCC.configure().sysclk(8.mhz()).freeze(&mut p.FLASH);
//!
//!     // This is used by `dht-sensor` to wait for signals
//!     let mut delay = delay::Delay::new(cp.SYST, &rcc);
//!
//!     // This could be any `gpio` port
//!     let gpio::gpioa::Parts { pa1, .. } = p.GPIOA.split(&mut rcc);
//!
//!     // An `Output<OpenDrain>` is both `InputPin` and `OutputPin`
//!     let mut pa1 = cortex_m::interrupt::free(|cs| pa1.into_open_drain_output(cs));
//!     
//!     // Pulling the pin high to avoid confusing the sensor when initializing
//!     pa1.set_high().ok();
//!
//!     // The DHT11 datasheet suggests 1 second
//!     hprintln!("Waiting on the sensor...").unwrap();
//!     delay.delay_ms(1000_u16);
//!     
//!     loop {
//!         match dht11::Reading::read(&mut delay, &mut pa1) {
//!             Ok(dht11::Reading {
//!                 temperature,
//!                 relative_humidity,
//!             }) => hprintln!("{}°, {}% RH", temperature, relative_humidity).unwrap(),
//!             Err(e) => hprintln!("Error {:?}", e).unwrap(),
//!         }
//!         
//!         // Delay of at least 500ms before polling the sensor again, 1 second or more advised
//!         delay.delay_ms(500_u16);  
//!     }
//! }
//! ```
#![cfg_attr(not(test), no_std)]

mod read;
pub use read::{Delay, DhtError, InputOutputPin};

pub trait DhtReading: internal::FromRaw + Sized {
    fn read<P, E>(delay: &mut dyn Delay, pin: &mut P) -> Result<Self, read::DhtError<E>>
    where
        P: InputOutputPin<E>,
    {
        read::read_raw(delay, pin).map(Self::raw_to_reading)
    }
}

mod internal {
    pub trait FromRaw {
        fn raw_to_reading(bytes: [u8; 4]) -> Self;
    }
}

pub mod dht11 {
    use super::*;

    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    pub struct Reading {
        pub temperature: i8,
        pub relative_humidity: u8,
    }

    impl internal::FromRaw for Reading {
        fn raw_to_reading(bytes: [u8; 4]) -> Reading {
            let [rh, _, temp_signed, _] = bytes;
            let temp = {
                let (signed, magnitude) = convert_signed(temp_signed);
                let temp_sign = if signed { -1 } else { 1 };
                temp_sign * magnitude as i8
            };
            Reading {
                temperature: temp,
                relative_humidity: rh,
            }
        }
    }

    impl DhtReading for Reading {}

    #[test]
    fn test_raw_to_reading() {
        use super::internal::FromRaw;

        assert_eq!(
            Reading::raw_to_reading([0x32, 0, 0x1B, 0]),
            Reading {
                temperature: 27,
                relative_humidity: 50
            }
        );
        assert_eq!(
            Reading::raw_to_reading([0x80, 0, 0x83, 0]),
            Reading {
                temperature: -3,
                relative_humidity: 128
            }
        );
    }
}

pub mod dht22 {
    use super::*;

    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct Reading {
        pub temperature: f32,
        pub relative_humidity: f32,
    }

    impl internal::FromRaw for Reading {
        fn raw_to_reading(bytes: [u8; 4]) -> Reading {
            let [rh_h, rh_l, temp_h_signed, temp_l] = bytes;
            let rh = ((rh_h as u16) << 8 | (rh_l as u16)) as f32 / 10.0;
            let temp = {
                let (signed, magnitude) = convert_signed(temp_h_signed);
                let temp_sign = if signed { -1.0 } else { 1.0 };
                let temp_magnitude = ((magnitude as u16) << 8) | temp_l as u16;
                temp_sign * temp_magnitude as f32 / 10.0
            };
            Reading {
                temperature: temp,
                relative_humidity: rh,
            }
        }
    }

    impl DhtReading for Reading {}

    #[test]
    fn test_raw_to_reading() {
        use super::internal::FromRaw;

        assert_eq!(
            Reading::raw_to_reading([0x02, 0x10, 0x01, 0x1B]),
            Reading {
                temperature: 28.3,
                relative_humidity: 52.8
            }
        );
        assert_eq!(
            Reading::raw_to_reading([0x02, 0x90, 0x80, 0x1B]),
            Reading {
                temperature: -2.7,
                relative_humidity: 65.6
            }
        );
    }
}

fn convert_signed(signed: u8) -> (bool, u8) {
    let sign = signed & 0x80 != 0;
    let magnitude = signed & 0x7F;
    (sign, magnitude)
}

#[test]
fn test_convert_signed() {
    assert_eq!(convert_signed(0x13), (false, 0x13));
    assert_eq!(convert_signed(0x93), (true, 0x13));
}