1
- use embassy_time:: { with_timeout, Duration , Instant } ;
2
1
use embedded_hal:: digital:: { InputPin , OutputPin } ;
3
2
use embedded_hal_async:: delay:: DelayNs ;
4
3
use embedded_hal_async:: digital:: Wait ;
5
4
6
5
/// How long to wait for a pulse on the data line (in microseconds).
7
- const TIMEOUT_US : u64 = 1_000 ;
6
+ const TIMEOUT_US : u32 = 1_000 ;
8
7
9
8
/// Error type for this crate.
10
9
#[ derive( Debug ) ]
@@ -50,18 +49,16 @@ where
50
49
/// Performs a reading of the sensor.
51
50
pub async fn read ( & mut self ) -> Result < Measurement , Error < E > > {
52
51
let mut data = [ 0u8 ; 5 ] ;
53
-
54
52
// Perform initial handshake
55
53
self . perform_handshake ( ) . await ?;
56
-
57
54
// Read bits
58
55
for i in 0 ..40 {
59
56
data[ i / 8 ] <<= 1 ;
60
57
if self . read_bit ( ) . await ? {
61
58
data[ i / 8 ] |= 1 ;
62
59
}
63
60
}
64
-
61
+ // Read bits
65
62
// Finally wait for line to go idle again.
66
63
self . wait_for_pulse ( true ) . await ?;
67
64
95
92
96
93
// As a response, the device pulls the line low for 80us and then high for 80us.
97
94
self . read_bit ( ) . await ?;
98
-
99
95
Ok ( ( ) )
100
96
}
101
97
@@ -105,25 +101,17 @@ where
105
101
Ok ( high > low)
106
102
}
107
103
108
- async fn wait_for_pulse ( & mut self , level : bool ) -> Result < u64 , Error < E > > {
109
- let timeout_duration = Duration :: from_micros ( TIMEOUT_US ) ;
110
- let start = Instant :: now ( ) ;
104
+ async fn wait_for_pulse ( & mut self , level : bool ) -> Result < u32 , Error < E > > {
105
+ let mut count = 0_u32 ;
111
106
112
- let wait_future = async {
113
- if level {
114
- self . gpio . wait_for_rising_edge ( ) . await . map_err ( Error :: Gpio )
115
- } else {
116
- self . gpio . wait_for_falling_edge ( ) . await . map_err ( Error :: Gpio )
107
+ while self . gpio . is_high ( ) . map_err ( Error :: Gpio ) ? != level {
108
+ count += 1 ;
109
+ if count > TIMEOUT_US {
110
+ return Err ( Error :: Timeout ) ;
117
111
}
118
- } ;
119
-
120
- // Wait for the pulse with timeout.
121
- with_timeout ( timeout_duration, wait_future)
122
- . await
123
- . map_err ( |_| Error :: Timeout ) ??;
124
- let elapsed = Instant :: now ( ) - start;
112
+ self . delay . delay_us ( 1 ) . await ;
113
+ }
125
114
126
- // Using microseconds for finer measurement.
127
- Ok ( elapsed. as_micros ( ) )
115
+ Ok ( count)
128
116
}
129
117
}
0 commit comments