Skip to content

Commit c85d8ab

Browse files
committed
Add RX interrupt support to serial_echo_rtic
1 parent a7b911e commit c85d8ab

File tree

1 file changed

+44
-5
lines changed

1 file changed

+44
-5
lines changed

examples/serial_echo_rtic.rs

Lines changed: 44 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,10 @@
33

44
extern crate panic_rtt_target;
55

6+
use heapless::{
7+
consts::U8,
8+
spsc,
9+
};
610
use nb::block;
711
use rtt_target::{
812
rprint,
@@ -26,10 +30,16 @@ const APP: () = {
2630
struct Resources {
2731
rx: serial::Rx<USART2>,
2832
tx: serial::Tx<USART2>,
33+
34+
rx_prod: spsc::Producer<'static, u8, U8>,
35+
rx_cons: spsc::Consumer<'static, u8, U8>,
2936
}
3037

3138
#[init]
3239
fn init(_: init::Context) -> init::LateResources {
40+
static mut RX_QUEUE: spsc::Queue<u8, U8> =
41+
spsc::Queue(heapless::i::Queue::new());
42+
3343
rtt_target::rtt_init_print!();
3444
rprint!("Initializing... ");
3545

@@ -46,32 +56,61 @@ const APP: () = {
4656
let tx_pin = gpioa.pa2.into_af7(&mut gpioa.moder, &mut gpioa.afrl);
4757
let rx_pin = gpioa.pa3.into_af7(&mut gpioa.moder, &mut gpioa.afrl);
4858

49-
let serial = Serial::usart2(
59+
let mut serial = Serial::usart2(
5060
p.USART2,
5161
(tx_pin, rx_pin),
5262
Config::default()
5363
.baudrate(115_200.bps()),
5464
clocks,
5565
&mut rcc.apb1r1,
5666
);
67+
serial.listen(serial::Event::Rxne);
68+
5769
let (tx, rx) = serial.split();
70+
let (rx_prod, rx_cons) = RX_QUEUE.split();
5871

5972
rprintln!("done.");
6073

6174
init::LateResources {
6275
rx,
6376
tx,
77+
78+
rx_prod,
79+
rx_cons,
6480
}
6581
}
6682

67-
#[idle(resources = [rx, tx])]
83+
#[idle(resources = [rx_cons, tx])]
6884
fn idle(cx: idle::Context) -> ! {
69-
let rx = cx.resources.rx;
85+
let rx = cx.resources.rx_cons;
7086
let tx = cx.resources.tx;
7187

7288
loop {
73-
let b = block!(rx.read()).unwrap();
74-
block!(tx.write(b)).unwrap();
89+
if let Some(b) = rx.dequeue() {
90+
rprintln!("Echoing '{}'", b as char);
91+
block!(tx.write(b)).unwrap();
92+
}
93+
}
94+
}
95+
96+
#[task(binds = USART2, resources = [rx, rx_prod])]
97+
fn usart2(cx: usart2::Context) {
98+
let rx = cx.resources.rx;
99+
let queue = cx.resources.rx_prod;
100+
101+
let b = match rx.read() {
102+
Ok(b) => b,
103+
Err(err) => {
104+
rprintln!("Error reading from USART: {:?}", err);
105+
return;
106+
}
107+
};
108+
match queue.enqueue(b) {
109+
Ok(()) => (),
110+
Err(err) => {
111+
rprintln!("Error adding received byte to queue: {:?}", err);
112+
return;
113+
}
75114
}
76115
}
77116
};

0 commit comments

Comments
 (0)