Crates.io | dht-embedded |
lib.rs | dht-embedded |
version | 0.4.0 |
source | src |
created_at | 2022-05-30 10:21:21.974343 |
updated_at | 2024-01-09 23:09:54.407067 |
description | Library for reading temperature and humidity from the DHT11 and DHT22 sensors |
homepage | https://github.com/kelnos/dht-embedded-rs |
repository | https://github.com/kelnos/dht-embedded-rs |
max_upload_size | |
id | 596893 |
size | 25,017 |
dht-embedded
is a Rust crate that reads temperature and humidity data
from the DHT11 and DHT22 sensors.
Add the following to your Cargo.toml
:
[dependencies]
dht-embedded = "0.4"
This crate depends on the stabilized 1.x series of embedded-hal
.
You will need to use an embedded-hal
implementation for your hardware.
Here's a simple one using linux-embedded-hal
and gpio-cdev
, which
could be used on a Rasperry Pi.
use dht_embedded::{Dht22, DhtSensor, NoopInterruptControl};
use gpio_cdev::{Chip, LineRequestFlags};
use linux_embedded_hal::{CdevPin, Delay};
use std::{thread::sleep, time::Duration};
fn main() -> anyhow::Result<()> {
let mut gpiochip = Chip::new("/dev/gpiochip0")?;
let line = gpiochip.get_line(17)?;
let handle = line.request(LineRequestFlags::INPUT | LineRequestFlags::OUTPUT, 1, "dht-sensor")?;
let pin = CdevPin::new(handle)?;
let mut sensor = Dht22::new(NoopInterruptControl, Delay, pin);
loop {
match sensor.read() {
Ok(reading) => println!("{}°C, {}% RH", reading.temperature(), reading.humidity()),
Err(e) => eprintln!("Error: {}", e),
}
sleep(Duration::from_millis(2100));
}
}
Note that, if your hardware supports it, you should set the GPIO pin to "open drain" mode.
(To be fair, the Linux kernel includes a driver for DHT sensors, and honestly it's probably better to use that driver, since kernel space can disable interrupts and get much more precise timing than we can.)
A search of crates.io might yield several different implementations of this driver. I wrote this because none of the others worked for me, and, upon examination of their code, I found they used a completely different protocols for reading from the sensor, protocols I couldn't find documented anywhere as what's supposed to work. This crate implements one of the simpler protocols that doesn't require access to a system clock, but still seems to work most of the time.