2019-03-12 01:23:52 +08:00
|
|
|
use stm32f4xx_hal::{
|
|
|
|
adc::{
|
|
|
|
Adc,
|
|
|
|
config::*,
|
|
|
|
},
|
|
|
|
gpio::{Analog, gpioa::PA3 as Pin},
|
|
|
|
stm32::ADC1 as ADC,
|
|
|
|
};
|
|
|
|
|
2019-03-19 03:56:29 +08:00
|
|
|
/// ADC Input
|
2019-03-12 01:23:52 +08:00
|
|
|
pub struct AdcInput {
|
|
|
|
/// unused but consumed
|
|
|
|
_pin: Pin<Analog>,
|
2019-03-19 03:56:29 +08:00
|
|
|
adc: Adc<ADC>,
|
2019-03-12 01:23:52 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
impl AdcInput {
|
2019-03-19 03:56:29 +08:00
|
|
|
/// 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)
|
2019-03-19 03:56:29 +08:00
|
|
|
.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 }
|
|
|
|
}
|
|
|
|
|
2019-03-19 03:56:29 +08:00
|
|
|
/// Enable the ADC,
|
|
|
|
/// run a conversion
|
|
|
|
/// disable the ADC
|
2019-03-12 01:23:52 +08:00
|
|
|
pub fn read(&mut self) -> u16 {
|
2019-03-19 03:56:29 +08:00
|
|
|
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
|
|
|
}
|
|
|
|
}
|