Skip to content

Commit a11dad6

Browse files
committed
feat: add waiting state; start communication
1 parent ef1634b commit a11dad6

File tree

3 files changed

+47
-8
lines changed

3 files changed

+47
-8
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# embedded-dht-rs
22

3+
![steps](/docs/steps.png)
34

45
## Step 1
56

docs/steps.png

29.4 KB
Loading

src/lib.rs

Lines changed: 46 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,56 @@
11
#![no_std]
22

3-
use embedded_hal::digital::{ErrorType, InputPin, OutputPin};
3+
use embedded_hal::{
4+
delay::DelayNs,
5+
digital::{ErrorType, InputPin, OutputPin, PinState},
6+
};
47

5-
pub struct Dht11<P: InputPin + OutputPin> {
6-
pin: P
8+
pub struct Dht11<P: InputPin + OutputPin, D: DelayNs> {
9+
pin: P,
10+
delay: D,
711
}
812

9-
impl<P: InputPin + OutputPin> Dht11<P> {
10-
11-
pub fn new(pin: P) -> Self {
12-
Self { pin }
13+
impl<P: InputPin + OutputPin, D: DelayNs> Dht11<P, D> {
14+
pub fn new(pin: P, delay: D) -> Self {
15+
Self { pin, delay }
1316
}
1417

1518
pub fn read(&mut self) -> Result<bool, <P as ErrorType>::Error> {
19+
// Start communication: pull pin low for 18ms, then release.
20+
let _ = self.pin.set_low();
21+
self.delay.delay_ms(18);
22+
let _ = self.pin.set_high();
23+
24+
// Wait for sensor to respond.
25+
self.delay.delay_us(48);
26+
27+
// Sync with sensor: wait for high then low signals.
28+
let _ = self.wait_until_state(PinState::High);
29+
let _ = self.wait_until_state(PinState::Low);
30+
31+
// Start reading
32+
33+
// TODO
34+
1635
return self.pin.is_high();
1736
}
18-
}
37+
38+
/// Waits until the pin reaches the specified state.
39+
///
40+
/// This helper function continuously polls the pin until it reaches the desired `PinState`.
41+
///
42+
/// # Arguments
43+
///
44+
/// * `state` - The target `PinState` to wait for (either `Low` or `High`).
45+
fn wait_until_state(&mut self, state: PinState) -> Result<(), <P as ErrorType>::Error>{
46+
loop {
47+
match state {
48+
PinState::Low => if self.pin.is_low()? { break; },
49+
PinState::High => if self.pin.is_high()? { break; }
50+
};
51+
self.delay.delay_us(1);
52+
}
53+
Ok(())
54+
}
55+
}
56+

0 commit comments

Comments
 (0)