use crate::lights::LED;
use ads1x1x::{
Ads1x1x, channel,
ic::{Ads1015, Resolution12Bit},
mode::Continuous,
};
use linux_embedded_hal::I2cdev;
use std::sync::{Arc, Mutex};
pub struct AnalogInput {
driver: Arc<Mutex<Ads1x1x<I2cdev, Ads1015, Resolution12Bit, Continuous>>>,
led: Option<LED>,
channel: u8,
pub value: f64,
pub max_value: f64,
}
impl AnalogInput {
pub fn new(
driver: Arc<Mutex<Ads1x1x<I2cdev, Ads1015, Resolution12Bit, Continuous>>>,
led: Option<LED>,
channel: u8,
) -> Self {
AnalogInput {
driver,
led,
channel,
value: 0.0,
max_value: 25.85,
}
}
pub fn read(&mut self) -> Result<f64, String> {
let mut driver = self.driver.lock().unwrap();
match self.channel {
0 => driver
.select_channel(channel::SingleA0)
.map_err(|error| format!("Failed to read value from channel 0: {:?}", error)),
1 => driver
.select_channel(channel::SingleA1)
.map_err(|error| format!("Failed to read value from channel 1: {:?}", error)),
2 => driver
.select_channel(channel::SingleA2)
.map_err(|error| format!("Failed to read value from channel 2: {:?}", error)),
3 => driver
.select_channel(channel::SingleA3)
.map_err(|error| format!("Failed to read value from channel 3: {:?}", error)),
_ => return Err("Invalid channel".to_string()),
}?;
let value = driver.read().unwrap();
self.value = ((value as f64 / 10.0) * 2.048) / self.max_value;
if self.led.is_some() {
if let Err(e) = self.led.as_mut().unwrap().set_brightness(self.value) {
return Err(format!("Failed to update LED: {}", e));
}
}
Ok(self.value)
}
}