Skip to main content

dht20/
sensor_reading.rs

1#[derive(Debug)]
2pub struct SensorReading {
3    temperature: f32, // represented internally in Celsius
4    humidity: f32,    // represented internally as percentage
5}
6
7impl SensorReading {
8    // constructor for DHTReading struct
9    pub fn new(temperature: f32, humidity: f32) -> Self {
10        Self {
11            temperature,
12            humidity,
13        }
14    }
15
16    // getter for humidity
17    // returns the humidity as a percentage; e.g. 60.0 for 60%.
18    // applicable values are 0% to 100%.
19    pub fn humidity(&self) -> f32 {
20        self.humidity
21    }
22
23    // getter for temperature value, in Celsius
24    // applicable values are -40C to 80C.
25    pub fn temperature_celsius(&self) -> f32 {
26        self.temperature
27    }
28
29    // getter for temperature value, in Fahrenheit
30    // applicable values are -40C to 80C.
31    pub fn temperature_fahrenheit(&self) -> f32 {
32        self.temperature * 9.0 / 5.0 + 32.0
33    }
34}
35
36#[cfg(test)]
37mod tests {
38    use super::*;
39
40    #[test]
41    fn test_dht_reading() {
42        let reading = SensorReading::new(25.0, 60.0);
43        assert_eq!(reading.temperature_celsius(), 25.0);
44        assert_eq!(reading.temperature_fahrenheit(), 77.0);
45        assert_eq!(reading.humidity(), 60.0);
46    }
47}