Skip to content

Commit cfc84ff

Browse files
committed
Add ADC continuous conversion example
1 parent 3e2437b commit cfc84ff

File tree

2 files changed

+96
-0
lines changed

2 files changed

+96
-0
lines changed

Cargo.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,10 @@ debug = true
262262
opt-level = "s"
263263

264264

265+
[[example]]
266+
name = "adc_cont"
267+
required-features = ["stm32l0x2"]
268+
265269
[[example]]
266270
name = "aes_ecb"
267271
required-features = ["stm32l082"]

examples/adc_cont.rs

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
//! Example showing continuous ADC
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+
use cortex_m_rt::entry;
17+
// use nb::block;
18+
use stm32l0xx_hal::{
19+
prelude::*,
20+
dma::DMA,
21+
pac,
22+
rcc,
23+
serial,
24+
};
25+
26+
27+
#[entry]
28+
fn main() -> ! {
29+
let dp = pac::Peripherals::take().unwrap();
30+
31+
let mut rcc = dp.RCC.freeze(rcc::Config::hsi16());
32+
let adc = dp.ADC.constrain(&mut rcc);
33+
let mut dma = DMA::new(dp.DMA1, &mut rcc);
34+
let gpioa = dp.GPIOA.split(&mut rcc);
35+
36+
// The A0 connector on the B-L072Z-LRWAN1 Discovery kit
37+
let a0 = gpioa.pa0.into_analog();
38+
39+
// Connected to the host computer via the ST-LINK
40+
let tx = gpioa.pa2;
41+
let rx = gpioa.pa3;
42+
43+
// Initialize USART for test output
44+
let (mut tx, _) = dp.USART2
45+
.usart(
46+
(tx, rx),
47+
serial::Config::default()
48+
.baudrate(115_200.bps()),
49+
&mut rcc,
50+
)
51+
.unwrap()
52+
.split();
53+
54+
// Create the buffer we're going to use for DMA.
55+
//
56+
// This is safe, since this is the main function, and it's only executed
57+
// once. This means there is no other code accessing this `static`.
58+
static mut BUFFER: [u16; 256] = [0; 256];
59+
let buffer = Pin::new(unsafe { &mut BUFFER });
60+
61+
// Start reading ADC values
62+
let mut adc = adc.start(
63+
a0,
64+
&mut dma.handle,
65+
dma.channels.channel1,
66+
buffer,
67+
);
68+
69+
loop {
70+
let read_available = match adc.read_available() {
71+
Ok(read_available) => {
72+
read_available
73+
}
74+
Err(err) => {
75+
write!(tx, "Error reading available values: {:?}\r\n", err).unwrap();
76+
continue;
77+
}
78+
};
79+
80+
for val in read_available {
81+
// Printing values out is way too slow to process all the values
82+
// being created, meaning we're going to see buffer overruns all the
83+
// time.
84+
//
85+
// For this reason, we're ignoring buffer overrun errors here, and
86+
// just process any values that were put into the buffer for us.
87+
if let Ok(val) = val {
88+
write!(tx, "{}\r\n", val).unwrap();
89+
}
90+
}
91+
}
92+
}

0 commit comments

Comments
 (0)