Skip to content

Commit ff2c58a

Browse files
committed
fix
1 parent 915727c commit ff2c58a

File tree

1 file changed

+11
-23
lines changed

1 file changed

+11
-23
lines changed

src/dht11.rs

+11-23
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
1-
use embassy_time::{with_timeout, Duration, Instant};
21
use embedded_hal::digital::{InputPin, OutputPin};
32
use embedded_hal_async::delay::DelayNs;
43
use embedded_hal_async::digital::Wait;
54

65
/// 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;
87

98
/// Error type for this crate.
109
#[derive(Debug)]
@@ -50,18 +49,16 @@ where
5049
/// Performs a reading of the sensor.
5150
pub async fn read(&mut self) -> Result<Measurement, Error<E>> {
5251
let mut data = [0u8; 5];
53-
5452
// Perform initial handshake
5553
self.perform_handshake().await?;
56-
5754
// Read bits
5855
for i in 0..40 {
5956
data[i / 8] <<= 1;
6057
if self.read_bit().await? {
6158
data[i / 8] |= 1;
6259
}
6360
}
64-
61+
// Read bits
6562
// Finally wait for line to go idle again.
6663
self.wait_for_pulse(true).await?;
6764

@@ -95,7 +92,6 @@ where
9592

9693
// As a response, the device pulls the line low for 80us and then high for 80us.
9794
self.read_bit().await?;
98-
9995
Ok(())
10096
}
10197

@@ -105,25 +101,17 @@ where
105101
Ok(high > low)
106102
}
107103

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;
111106

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);
117111
}
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+
}
125114

126-
// Using microseconds for finer measurement.
127-
Ok(elapsed.as_micros())
115+
Ok(count)
128116
}
129117
}

0 commit comments

Comments
 (0)