Skip to content

Commit 3416705

Browse files
committed
Add example for ADC multi-channel conversions
1 parent f359dd3 commit 3416705

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed

examples/adc_multi.rs

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
//! Example showing continuous ADC with hardware trigger
2+
3+
4+
#![no_main]
5+
#![no_std]
6+
7+
8+
extern crate panic_halt;
9+
10+
11+
use core::{
12+
fmt::Write as _,
13+
pin::Pin,
14+
};
15+
16+
17+
use cortex_m_rt::entry;
18+
use stm32l0xx_hal::{
19+
prelude::*,
20+
adc,
21+
dma::DMA,
22+
pac::{
23+
self,
24+
tim2::cr2::MMS_A,
25+
},
26+
rcc,
27+
serial,
28+
};
29+
30+
31+
#[entry]
32+
fn main() -> ! {
33+
let dp = pac::Peripherals::take().unwrap();
34+
35+
let mut rcc = dp.RCC.freeze(rcc::Config::hsi16());
36+
let adc = dp.ADC.constrain(&mut rcc);
37+
let mut dma = DMA::new(dp.DMA1, &mut rcc);
38+
let gpioa = dp.GPIOA.split(&mut rcc);
39+
40+
// Connected to the host computer via the ST-LINK
41+
let tx = gpioa.pa2;
42+
let rx = gpioa.pa3;
43+
44+
// Initialize USART for test output
45+
let (mut tx, _) = dp.USART2
46+
.usart(
47+
(tx, rx),
48+
serial::Config::default()
49+
.baudrate(115_200.bps()),
50+
&mut rcc,
51+
)
52+
.unwrap()
53+
.split();
54+
55+
// Create the buffer we're going to use for DMA.
56+
//
57+
// This is safe, since this is the main function, and it's only executed
58+
// once. This means there is no other code accessing this `static`.
59+
static mut BUFFER: [u16; 256] = [0; 256];
60+
let buffer = Pin::new(unsafe { &mut BUFFER });
61+
62+
// Let's select some channels
63+
let mut channels = adc::Channels::from(gpioa.pa0.into_analog());
64+
channels.add(gpioa.pa1.into_analog());
65+
channels.add(gpioa.pa4.into_analog());
66+
channels.add(gpioa.pa5.into_analog());
67+
68+
// Start reading ADC values
69+
let mut adc = adc.start(
70+
channels,
71+
Some(adc::Trigger::TIM2_TRGO),
72+
&mut dma.handle,
73+
dma.channels.channel1,
74+
buffer,
75+
);
76+
77+
// Enable trigger output for TIM2. This must happen after ADC has been
78+
// configured.
79+
dp.TIM2
80+
.timer(1u32.hz(), &mut rcc)
81+
.select_master_mode(MMS_A::UPDATE);
82+
83+
loop {
84+
for val in adc.read_available().unwrap() {
85+
write!(tx, "{}\r\n", val.unwrap()).unwrap();
86+
}
87+
}
88+
}

0 commit comments

Comments
 (0)