Skip to content

Commit

Permalink
Refactor DHT11 sensor handling and ensure safe GPIO pin state on drop
Browse files Browse the repository at this point in the history
  • Loading branch information
psytraxx committed Jan 21, 2025
1 parent 3de81b9 commit baeb8c2
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
13 changes: 13 additions & 0 deletions src/dht11.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ pub enum Error<E> {
/// A DHT11 device.
pub struct Dht11<GPIO, D>
where
GPIO: InputPin + OutputPin,
D: DelayNs,
{
/// The concrete GPIO pin implementation.
Expand Down Expand Up @@ -118,3 +119,15 @@ where
Ok(u32::from(count))
}
}

impl<GPIO, D, E> Drop for Dht11<GPIO, D>
where
GPIO: InputPin<Error = E> + OutputPin<Error = E>,
D: DelayNs,
{
fn drop(&mut self) {
// Set pin high (floating with pull-up) as safe state
// Ignore errors during drop
let _ = self.gpio.set_high();
}
}
9 changes: 4 additions & 5 deletions src/sensors_task.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,16 +38,12 @@ pub struct SensorPeripherals {
#[embassy_executor::task]
pub async fn sensor_task(
sender: Sender<'static, NoopRawMutex, SensorData, 3>,
p: SensorPeripherals,
mut p: SensorPeripherals,
) {
info!("Create");

let dht11_pin = OutputOpenDrain::new(p.dht11_pin, Level::High, Pull::None);

let delay = Delay::new();

let mut dht11_sensor = Dht11::new(dht11_pin, delay);

let mut adc2_config = AdcConfig::new();
let mut moisture_pin = adc2_config
.enable_pin_with_cal::<_, AdcCalCurve<ADC2>>(p.moisture_analog_pin, Attenuation::_11dB);
Expand All @@ -70,6 +66,9 @@ pub async fn sensor_task(
let mut battery_voltage_samples: vec::Vec<u16> = vec![];
let mut water_level_samples: vec::Vec<u16> = vec![];

let dht11_pin = OutputOpenDrain::new(&mut p.dht11_pin, Level::High, Pull::None);
let mut dht11_sensor: Dht11<OutputOpenDrain<'_>, Delay> = Dht11::new(dht11_pin, delay);

for i in 0..SENSOR_SAMPLE_COUNT {
info!("Reading sensor data {}/{}", (i + 1), SENSOR_SAMPLE_COUNT);

Expand Down

0 comments on commit baeb8c2

Please sign in to comment.