Skip to content

Commit 60917f8

Browse files
committed
feat: add timeout for wait_until_state
1 parent d40e257 commit 60917f8

File tree

2 files changed

+20
-8
lines changed

2 files changed

+20
-8
lines changed

src/dht.rs

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ use embedded_hal::{
55

66
use crate::SensorError;
77

8+
const DEFAULT_MAX_ATTEMPTS: usize = 10_000;
9+
810
/// Common base struct for DHT11, DHT22 sensors.
911
pub struct Dht<P: InputPin + OutputPin, D: DelayNs> {
1012
pub pin: P,
@@ -61,16 +63,24 @@ impl<P: InputPin + OutputPin, D: DelayNs> Dht<P, D> {
6163
/// # Returns
6264
///
6365
/// - `Ok(())`: When the pin reaches the desired state.
64-
/// - `Err(SensorError<P::Error>)`: If an error occurs while reading the pin state.
66+
/// - `Err(SensorError::Timeout)`: If the desired state is not reached in time.
67+
/// - `Err(SensorError::Io(...))`: If a pin error occurs while reading the pin state.
6568
///
66-
pub fn wait_until_state(&mut self, state: PinState) -> Result<(), <P as ErrorType>::Error> {
67-
while !match state {
68-
PinState::Low => self.pin.is_low(),
69-
PinState::High => self.pin.is_high(),
70-
}? {
71-
self.delay.delay_us(1);
69+
pub fn wait_until_state(&mut self, state: PinState) -> Result<(), SensorError> {
70+
for _ in 0..DEFAULT_MAX_ATTEMPTS {
71+
let is_state = match state {
72+
PinState::Low => self.pin.is_low(),
73+
PinState::High => self.pin.is_high(),
74+
};
75+
76+
match is_state {
77+
Ok(true) => return Ok(()),
78+
Ok(false) => self.delay.delay_us(1),
79+
Err(_) => return Err(SensorError::PinError)
80+
}
7281
}
73-
Ok(())
82+
83+
Err(SensorError::Timeout)
7484
}
7585
}
7686

src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,6 @@ pub struct SensorReading<T> {
2222
#[derive(Debug)]
2323
pub enum SensorError {
2424
ChecksumMismatch,
25+
Timeout,
26+
PinError
2527
}

0 commit comments

Comments
 (0)