-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhw390.rs
48 lines (46 loc) · 1.6 KB
/
hw390.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
use crate::Data;
use alloc::string::ToString;
use embedded_hal::adc::OneShot;
use esp_println::println;
use hal::adc::{AdcPin, ADC, ADC1};
use hal::gpio::{
Analog, Bank0GpioRegisterAccess, Gpio2Signals, GpioPin, InputOutputAnalogPinType,
SingleCoreInteruptStatusRegisterAccessBank0,
};
/// A struct containing the hardware(via pointers to the right addresses of course) for the hw390 moisture sensor
pub struct Hw390<'a> {
pub adc: ADC<'a, ADC1>,
pub pin: AdcPin<
GpioPin<
Analog,
Bank0GpioRegisterAccess,
SingleCoreInteruptStatusRegisterAccessBank0,
InputOutputAnalogPinType,
Gpio2Signals,
2,
>,
ADC1,
>,
}
impl<'a> Hw390<'a> {
/// Read out moisture data from the hw390 sensor and normalise it
pub fn read(&mut self) -> Data {
let readout = hal::prelude::nb::block!(self.adc.read(&mut self.pin)).unwrap();
Data {
r#type: "soil-moisture".to_string(),
value: normalise_humidity_data(readout),
}
}
}
/// The hw390 moisture sensor returns a value between 3000 and 4095
/// From our measurements the sensor was in water at 3000 and in air at 4095
/// We want to normalise the values to be between 0 and 1, so that 1 is in water and 0 is in air
fn normalise_humidity_data(readout: u16) -> f32 {
println!("HW390 readout: {}", readout);
let min_value = 3000;
let max_value = 4095;
let normalized_value =
(readout.saturating_sub(min_value)) as f32 / (max_value - min_value) as f32;
// And now invert the value
1.0 - normalized_value
}