cu_bdshot/
esc_channel.rs

1use hal::dma::TransferSize;
2use hal::pio::Running;
3use hal::pio::StateMachine;
4use hal::pio::{PIOExt, Rx, StateMachineIndex, Tx, ValidStateMachine};
5use rp235x_hal as hal;
6
7pub struct EscChannel<P, SM, TxSize, RxSize>
8where
9    P: PIOExt,
10    SM: StateMachineIndex,
11    (P, SM): ValidStateMachine,
12    TxSize: TransferSize,
13    RxSize: TransferSize,
14{
15    pub tx: Tx<(P, SM), TxSize>,
16    pub rx: Rx<(P, SM), RxSize>,
17    pub run: StateMachine<(P, SM), Running>,
18}
19
20impl<P, SM, TxSize, RxSize> EscChannel<P, SM, TxSize, RxSize>
21where
22    P: PIOExt,
23    SM: StateMachineIndex,
24    (P, SM): ValidStateMachine,
25    TxSize: TransferSize,
26    RxSize: TransferSize,
27{
28    pub fn is_full(&self) -> bool {
29        self.tx.is_full()
30    }
31
32    pub fn write(&mut self, v: u32) -> bool {
33        self.tx.write(v)
34    }
35
36    pub fn read(&mut self) -> Option<u32> {
37        self.rx.read()
38    }
39
40    pub fn restart(&mut self) {
41        self.run.restart()
42    }
43}
44
45/// Helper to DRY on the initialization of each channel for each ESC
46#[macro_export]
47macro_rules! build_ch {
48    ($prog:expr, $sm:ident, $pin:expr, $d:expr, $f:expr) => {{
49        #[allow(clippy::macro_metavars_in_unsafe)]
50        let (sm, rx, tx) = PIOBuilder::from_installed_program(unsafe { $prog.share() })
51            .set_pins($pin, 1)
52            .out_pins($pin, 1)
53            .out_shift_direction(hal::pio::ShiftDirection::Left)
54            .in_shift_direction(hal::pio::ShiftDirection::Left)
55            .in_pin_base($pin)
56            .jmp_pin($pin)
57            .clock_divisor_fixed_point($d, $f)
58            .autopush(true)
59            // A telemetry response is encoded over 21 bits (Then distilled to
60            // 16 bits accounting for encoding and redundancy)
61            .push_threshold(21)
62            .side_set_pin_base($pin)
63            .build($sm);
64        EscChannel {
65            tx,
66            rx,
67            run: sm.start(),
68        }
69    }};
70}