forked from stm32-rs/stm32h7xx-hal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
adc.rs
80 lines (63 loc) · 2.23 KB
/
adc.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
//! Example of reading a voltage with ADC1
//!
//! For an example of using ADC3, see examples/temperature.rs
//! For an example of using ADC1 and ADC2 together, see examples/adc12.rs
//! For an example of using ADC1 and ADC2 in parallel, see examples/adc12_parallel.rs
#![no_main]
#![no_std]
use log::info;
use cortex_m_rt::entry;
use stm32h7xx_hal::{adc, delay::Delay, pac, prelude::*, rcc::rec::AdcClkSel};
#[macro_use]
mod utilities;
#[entry]
fn main() -> ! {
utilities::logger::init();
let cp = cortex_m::Peripherals::take().unwrap();
let dp = pac::Peripherals::take().unwrap();
// Constrain and Freeze power
info!("Setup PWR... ");
let pwr = dp.PWR.constrain();
let pwrcfg = example_power!(pwr).freeze();
// Constrain and Freeze clock
info!("Setup RCC... ");
let rcc = dp.RCC.constrain();
// We need to configure a clock for adc_ker_ck_input. The default
// adc_ker_ck_input is pll2_p_ck, but we will use per_ck. per_ck is sourced
// from the 64MHz HSI
//
// adc_ker_ck_input is then divided by the ADC prescaler to give f_adc. The
// maximum f_adc is 50MHz
let mut ccdr = rcc.sys_ck(100.MHz()).freeze(pwrcfg, &dp.SYSCFG);
// Switch adc_ker_ck_input multiplexer to per_ck
ccdr.peripheral.kernel_adc_clk_mux(AdcClkSel::Per);
info!("");
info!("stm32h7xx-hal example - ADC");
info!("");
let mut delay = Delay::new(cp.SYST, ccdr.clocks);
// Setup ADC
let mut adc1 = adc::Adc::adc1(
dp.ADC1,
4.MHz(),
&mut delay,
ccdr.peripheral.ADC12,
&ccdr.clocks,
)
.enable();
adc1.set_resolution(adc::Resolution::SixteenBit);
// We can't use ADC2 here because ccdr.peripheral.ADC12 has been
// consumed. See examples/adc12.rs
// Setup GPIOC
let gpioc = dp.GPIOC.split(ccdr.peripheral.GPIOC);
// Configure pc0 as an analog input
let mut channel = gpioc.pc0.into_analog(); // ANALOG IN 10
loop {
let data: u32 = adc1.read(&mut channel).unwrap();
// voltage = reading * (vref/resolution)
info!(
"ADC reading: {}, voltage for nucleo: {}",
data,
data as f32 * (3.3 / adc1.slope() as f32)
);
}
}