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