|
| 1 | +# dht-embedded |
| 2 | + |
| 3 | +`dht-embedded` is a Rust crate that reads temperature and humidity data |
| 4 | +from the DHT11 and DHT22 sensors. |
| 5 | + |
| 6 | +## Prerequisites |
| 7 | + |
| 8 | +* You've connected the DHT sensor to your device (such as a Raspberry |
| 9 | + Pi or ESP32) using a GPIO pin. |
| 10 | + |
| 11 | +## Usage |
| 12 | + |
| 13 | +Add the following to your `Cargo.toml`: |
| 14 | + |
| 15 | +```toml |
| 16 | +[dependencies] |
| 17 | +dht-embedded = "=0.1.0-alpha.1" |
| 18 | +``` |
| 19 | + |
| 20 | +Note that this crate currently tracks the 1.0.0 alpha releases of |
| 21 | +`embedded-hal`, so things can change & break often, and your platform's |
| 22 | +`embedded-hal` implementation may not have trait impls for 1.0.0 alphas |
| 23 | +at all, let alone the current one this crate supports. |
| 24 | + |
| 25 | +You will need to use an `embedded-hal` implementation for your hardware. |
| 26 | +Here's a simple one using `linux-embedded-hal` and `gpio-cdev, which |
| 27 | +could be used on a Rasperry Pi. |
| 28 | + |
| 29 | +```rust,no_run,ignore |
| 30 | +use dht_embedded::{Dht22, DhtSensor, NoopInterruptControl}; |
| 31 | +use gpio_cdev::{Chip, LineRequestFlags}; |
| 32 | +use linux_embedded_hal::{CdevPin, Delay}; |
| 33 | +use std::{thread::sleep, time::Duration}; |
| 34 | +
|
| 35 | +fn main() -> anyhow::Result<()> { |
| 36 | + let mut gpiochip = Chip::new("/dev/gpiochip0")?; |
| 37 | + let line = gpiochip.get_line(17)?; |
| 38 | + let handle = line.request(LineRequestFlags::INPUT | LineRequestFlags::OUTPUT, 1, "dht-sensor")?; |
| 39 | + let pin = CdevPin::new(handle)?; |
| 40 | + let mut sensor = Dht22::new(NoopInterruptControl, Delay, pin); |
| 41 | +
|
| 42 | + loop { |
| 43 | + match sensor.read() { |
| 44 | + Ok(reading) => println!("{}°C, {}% RH", reading.temperature(), reading.humidity()), |
| 45 | + Err(e) => eprintln!("Error: {}", e), |
| 46 | + } |
| 47 | +
|
| 48 | + sleep(Duration::from_millis(2100)); |
| 49 | + } |
| 50 | +} |
| 51 | +``` |
| 52 | + |
| 53 | +(To be fair, the Linux kernel includes a driver for DHT sensors, and |
| 54 | +honestly it's probably better to use that driver, since kernel space can |
| 55 | +disable interrupts and get much more precise timing than we can.) |
| 56 | + |
| 57 | +## Why |
| 58 | + |
| 59 | +A search of crates.io might yield several different implementations of |
| 60 | +this driver. I wrote this because none of the others worked for me, |
| 61 | +and, upon examination of their code, I found they used a completely |
| 62 | +different protocols for reading from the sensor, protocols I couldn't |
| 63 | +find documented anywhere as what's supposed to work. This crate |
| 64 | +implements one of the simpler protocols that doesn't require access to a |
| 65 | +system clock, but still seems to work most of the time. |
0 commit comments