-
Notifications
You must be signed in to change notification settings - Fork 182
/
Copy pathcan-rtic.rs
250 lines (214 loc) · 8.12 KB
/
can-rtic.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
//! Interrupt driven CAN transmitter with RTIC.
//!
//! CAN frames are allocated from a static memory pool and stored in a priority
//! queue (min heap) for transmisison. To start transmission the CAN TX
//! interrupt has to be triggered manually once. With each successful
//! transmission the interrupt is reentered and more data is fetched from the
//! queue.
//! Received frames are simply echoed back. In contrast to the naive `can-echo`
//! example all messages are also correctly prioritized by the transmit queue.
#![no_main]
#![no_std]
use panic_halt as _;
use bxcan::Frame;
use core::cmp::Ordering;
use heapless::binary_heap::{BinaryHeap, Max};
use stm32f1xx_hal::pac::Interrupt;
#[derive(Debug)]
pub struct PriorityFrame(Frame);
/// Ordering is based on the Identifier and frame type (data vs. remote) and can be used to sort
/// frames by priority.
impl Ord for PriorityFrame {
fn cmp(&self, other: &Self) -> Ordering {
self.0.priority().cmp(&other.0.priority())
}
}
impl PartialOrd for PriorityFrame {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for PriorityFrame {
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == Ordering::Equal
}
}
impl Eq for PriorityFrame {}
fn enqueue_frame(queue: &mut BinaryHeap<PriorityFrame, Max, 16>, frame: Frame) {
queue.push(PriorityFrame(frame)).unwrap();
rtic::pend(Interrupt::USB_HP_CAN_TX);
}
#[rtic::app(device = stm32f1xx_hal::pac)]
mod app {
use super::{enqueue_frame, PriorityFrame};
use bxcan::{filter::Mask32, ExtendedId, Fifo, Frame, Interrupts, Rx0, StandardId, Tx};
use heapless::binary_heap::{BinaryHeap, Max};
use stm32f1xx_hal::{can::Can, pac::CAN1, prelude::*};
#[local]
struct Local {
can_tx: Tx<Can<CAN1>>,
can_rx: Rx0<Can<CAN1>>,
}
#[shared]
struct Shared {
can_tx_queue: BinaryHeap<PriorityFrame, Max, 16>,
tx_count: usize,
}
#[init]
fn init(cx: init::Context) -> (Shared, Local, init::Monotonics) {
let mut flash = cx.device.FLASH.constrain();
let rcc = cx.device.RCC.constrain();
let _clocks = rcc
.cfgr
.use_hse(8.MHz())
.sysclk(64.MHz())
.hclk(64.MHz())
.pclk1(16.MHz())
.pclk2(64.MHz())
.freeze(&mut flash.acr);
// Select pins for CAN1.
let gpioa = cx.device.GPIOA.split();
let can_rx_pin = gpioa.pa11;
let can_tx_pin = gpioa.pa12;
#[cfg(not(feature = "connectivity"))]
let can = Can::new(cx.device.CAN1, cx.device.USB, (can_tx_pin, can_rx_pin));
#[cfg(feature = "connectivity")]
let can = Can::new(cx.device.CAN1, (can_tx_pin, can_rx_pin));
// APB1 (PCLK1): 16MHz, Bit rate: 1000kBit/s, Sample Point 87.5%
// Value was calculated with http://www.bittiming.can-wiki.info/
let mut can = bxcan::Can::builder(can)
.set_bit_timing(0x001c_0000)
.leave_disabled();
can.modify_filters()
.enable_bank(0, Fifo::Fifo0, Mask32::accept_all());
// Sync to the bus and start normal operation.
can.enable_interrupts(
Interrupts::TRANSMIT_MAILBOX_EMPTY | Interrupts::FIFO0_MESSAGE_PENDING,
);
nb::block!(can.enable_non_blocking()).unwrap();
let (can_tx, can_rx, _) = can.split();
let can_tx_queue = BinaryHeap::new();
(
Shared {
can_tx_queue,
tx_count: 0,
},
Local { can_tx, can_rx },
init::Monotonics(),
)
}
#[idle(shared = [can_tx_queue, tx_count])]
fn idle(mut cx: idle::Context) -> ! {
let mut tx_queue = cx.shared.can_tx_queue;
// Enqueue some messages. Higher ID means lower priority.
tx_queue.lock(|mut tx_queue| {
enqueue_frame(
&mut tx_queue,
Frame::new_data(StandardId::new(9).unwrap(), []),
);
enqueue_frame(
&mut tx_queue,
Frame::new_data(ExtendedId::new(9).unwrap(), []),
);
enqueue_frame(
&mut tx_queue,
Frame::new_data(StandardId::new(8).unwrap(), []),
);
enqueue_frame(
&mut tx_queue,
Frame::new_data(ExtendedId::new(8).unwrap(), []),
);
enqueue_frame(
&mut tx_queue,
Frame::new_data(StandardId::new(0x7FF).unwrap(), []),
);
enqueue_frame(
&mut tx_queue,
Frame::new_data(ExtendedId::new(0x1FFF_FFFF).unwrap(), []),
);
});
// Add some higher priority messages when 3 messages have been sent.
loop {
let tx_count = cx.shared.tx_count.lock(|tx_count| *tx_count);
if tx_count >= 3 {
tx_queue.lock(|mut tx_queue| {
enqueue_frame(
&mut tx_queue,
Frame::new_data(StandardId::new(3).unwrap(), []),
);
enqueue_frame(
&mut tx_queue,
Frame::new_data(StandardId::new(2).unwrap(), []),
);
enqueue_frame(
&mut tx_queue,
Frame::new_data(StandardId::new(1).unwrap(), []),
);
});
break;
}
}
// Expected bus traffic:
//
// 1. ID: 0x00000008 <- proper reordering happens
// 2. ID: 0x00000009
// 3. ID: 0x008
// 4. ID: 0x001 <- higher priority messages injected correctly
// 5. ID: 0x002
// 6. ID: 0x003
// 7. ID: 0x009
// 8. ID: 0x7FF
// 9. ID: 0x1FFFFFFF
//
// The output can look different if there are other nodes on bus the sending messages.
loop {
cortex_m::asm::nop();
}
}
// This ISR is triggered by each finished frame transmission.
#[task(binds = USB_HP_CAN_TX, local = [can_tx], shared = [can_tx_queue, tx_count])]
fn can_tx(cx: can_tx::Context) {
let tx = cx.local.can_tx;
let mut tx_queue = cx.shared.can_tx_queue;
let mut tx_count = cx.shared.tx_count;
tx.clear_interrupt_flags();
// There is now a free mailbox. Try to transmit pending frames until either
// the queue is empty or transmission would block the execution of this ISR.
(&mut tx_queue, &mut tx_count).lock(|tx_queue, tx_count| {
while let Some(frame) = tx_queue.peek() {
match tx.transmit(&frame.0) {
Ok(status) => match status.dequeued_frame() {
None => {
// Frame was successfully placed into a transmit buffer.
tx_queue.pop();
*tx_count += 1;
}
Some(pending_frame) => {
// A lower priority frame was replaced with our high priority frame.
// Put the low priority frame back in the transmit queue.
tx_queue.pop();
enqueue_frame(tx_queue, pending_frame.clone());
}
},
Err(nb::Error::WouldBlock) => break,
Err(_) => unreachable!(),
}
}
});
}
#[task(binds = USB_LP_CAN_RX0, local = [can_rx], shared = [can_tx_queue])]
fn can_rx0(mut cx: can_rx0::Context) {
// Echo back received packages with correct priority ordering.
loop {
match cx.local.can_rx.receive() {
Ok(frame) => {
cx.shared.can_tx_queue.lock(|can_tx_queue| {
enqueue_frame(can_tx_queue, frame);
});
}
Err(nb::Error::WouldBlock) => break,
Err(nb::Error::Other(_)) => {} // Ignore overrun errors.
}
}
}
}