thermostat/src/adc_input.rs

47 lines
1.1 KiB
Rust
Raw Normal View History

2019-03-12 01:23:52 +08:00
use stm32f4xx_hal::{
adc::{
Adc,
config::*,
},
gpio::{Analog, gpioa::PA3 as Pin},
stm32::ADC1 as ADC,
};
/// ADC Input
2019-03-12 01:23:52 +08:00
pub struct AdcInput {
/// unused but consumed
_pin: Pin<Analog>,
adc: Adc<ADC>,
2019-03-12 01:23:52 +08:00
}
impl AdcInput {
/// Configure pin into analog mode
2019-03-12 01:23:52 +08:00
pub fn new<MODE>(adc: ADC, pin: Pin<MODE>) -> Self {
let pin = pin.into_analog();
let adc_config = AdcConfig::default()
.scan(Scan::Enabled)
.continuous(Continuous::Single)
.clock(Clock::Pclk2_div_2);
2019-03-12 01:23:52 +08:00
let mut adc = Adc::adc1(adc, true, adc_config);
adc.configure_channel(&pin, Sequence::One, SampleTime::Cycles_480);
AdcInput { _pin: pin, adc }
}
/// Enable the ADC,
/// run a conversion
/// disable the ADC
2019-03-12 01:23:52 +08:00
pub fn read(&mut self) -> u16 {
let adc = &mut self.adc;
adc.enable();
adc.clear_end_of_conversion_flag();
adc.start_conversion();
let sample = adc.current_sample();
let result = adc.sample_to_millivolts(sample);
adc.wait_for_conversion_sequence();
adc.disable();
result
2019-03-12 01:23:52 +08:00
}
}