#![no_std]
#![no_main]
use defmt_rtt as _;
use panic_probe as _;
use core::cell::RefCell;
use cortex_m::asm;
use cortex_m_rt::entry;
use critical_section::Mutex;
use embedded_hal::adc::OneShot;
use stm32f3xx_hal::{
adc,
pac::{self, interrupt},
prelude::*,
timer,
};
static TIMER: Mutex<RefCell<Option<timer::Timer<pac::TIM2>>>> = Mutex::new(RefCell::new(None));
#[entry]
fn main() -> ! {
let dp = pac::Peripherals::take().unwrap();
let mut rcc = dp.RCC.constrain();
let clocks = rcc.cfgr.freeze(&mut dp.FLASH.constrain().acr);
dp.DBGMCU.cr.modify(|_, w| {
w.dbg_sleep().set_bit();
w.dbg_standby().set_bit();
w.dbg_stop().set_bit()
});
let mut adc_common = adc::CommonAdc::new(dp.ADC1_2, &clocks, &mut rcc.ahb);
let mut tuple = (dp.ADC1, dp.ADC2);
let mut ts = adc::TemperatureSensor::new(&mut adc_common, &mut tuple);
let mut adc = adc::Adc::new(
tuple.0, adc::config::Config::default(),
&clocks,
&adc_common,
)
.into_oneshot();
let mut adc2 = adc::Adc::new_disabled(tuple.1);
adc2.calibrate(&clocks, &adc_common);
adc2.set_config(adc::config::Config::default());
let _ = adc2.into_enabled();
let mut gpioa = dp.GPIOA.split(&mut rcc.ahb);
let mut analog_pin = gpioa.pa0.into_analog(&mut gpioa.moder, &mut gpioa.pupdr);
let mut timer = timer::Timer::new(dp.TIM2, clocks, &mut rcc.apb1);
unsafe {
cortex_m::peripheral::NVIC::unmask(timer.interrupt());
}
timer.enable_interrupt(timer::Event::Update);
timer.start(500.milliseconds());
critical_section::with(|cs| {
TIMER.borrow(cs).replace(Some(timer));
});
defmt::info!("
The ADC has a 12 bit resolution, i.e. if your reference Value is 3V:
approx. ADC value | approx. volt value
==================+===================
0 | 0 mV
2048 | 1500 mV
4095 | 3000 mV
If you are using a STM32F3Discovery, PA0 is connected to the User Button.
Pressing it should connect the user Button to to HIGH and the value should change from 0 to 4095.
");
loop {
let adc_data: u16 = adc.read(&mut analog_pin).unwrap();
defmt::trace!("PA0 reads {}", adc_data);
let adc_data: u16 = adc.read(&mut ts).unwrap();
defmt::trace!("TemperatureSensor reads {}", adc_data);
asm::wfi();
}
}
#[interrupt]
fn TIM2() {
critical_section::with(|cs| {
TIMER
.borrow(cs)
.borrow_mut()
.as_mut()
.unwrap()
.clear_event(timer::Event::Update);
})
}