bluepill-rust-blinky/bluepill-rs/src/dmx.rs

58 lines
1.7 KiB
Rust
Raw Normal View History

2024-03-21 14:29:37 +00:00
use cortex_m::singleton;
2024-03-21 18:52:04 +00:00
use stm32f1xx_hal::{dma, pac, prelude::*, rcc, serial};
2024-03-21 17:58:02 +00:00
2024-03-22 00:11:17 +00:00
const DMX_LEN_MAX: usize = 512;
type TxDma = dma::TxDma<serial::Tx<pac::USART1>, dma::dma1::C4>;
type DMXUniverse<const DMX_LEN: usize> = &'static mut [u8; DMX_LEN];
type DMXTransfer<const DMX_LEN: usize> = dma::Transfer<dma::R, DMXUniverse<DMX_LEN>, TxDma>;
2024-03-21 14:29:37 +00:00
2024-03-23 14:54:36 +00:00
pub enum DMX<const DMX_LEN: usize = DMX_LEN_MAX> {
2024-03-22 00:11:17 +00:00
Idle(Option<TxDma>, Option<DMXUniverse<DMX_LEN>>),
Busy(Option<DMXTransfer<DMX_LEN>>),
2024-03-21 17:58:02 +00:00
}
2024-03-21 23:31:59 +00:00
impl<const DMX_LEN: usize> DMX<DMX_LEN> {
2024-03-21 17:58:02 +00:00
pub fn new<PINS>(
2024-03-21 18:52:04 +00:00
mut serial: serial::Serial<pac::USART1, PINS>,
2024-03-21 14:29:37 +00:00
channel: dma::dma1::C4,
clocks: &rcc::Clocks,
2024-03-21 17:58:02 +00:00
) -> Self
where
PINS: serial::Pins<pac::USART1>,
{
2024-03-23 14:54:36 +00:00
assert!(DMX_LEN <= DMX_LEN_MAX);
2024-03-21 19:23:06 +00:00
serial.reconfigure(250_000.bps(), &clocks).unwrap();
2024-03-21 14:29:37 +00:00
2024-03-21 23:35:46 +00:00
Self::Idle(Some(serial.tx.with_dma(channel)), None)
2024-03-21 14:29:37 +00:00
}
2024-03-22 00:11:17 +00:00
pub fn send(&mut self, data: &[u8]) {
2024-03-21 22:50:21 +00:00
if let Self::Busy(_) = self {
self.wait();
2024-03-21 17:58:02 +00:00
}
2024-03-21 22:50:21 +00:00
2024-03-21 23:35:46 +00:00
let Self::Idle(tx, txbuffer) = self else {
2024-03-21 22:50:21 +00:00
panic!("Broken DMX State!")
};
2024-03-21 23:35:46 +00:00
let txbuffer = txbuffer.take().unwrap_or_else(|| {
2024-03-22 00:11:17 +00:00
let foo = singleton!(: [u8; DMX_LEN_MAX] = [0u8; DMX_LEN_MAX]).unwrap();
2024-03-21 23:31:59 +00:00
(&mut foo[..DMX_LEN]).try_into().unwrap()
});
2024-03-21 23:35:46 +00:00
let tx = tx.take().unwrap();
2024-03-21 22:50:21 +00:00
2024-03-22 00:11:17 +00:00
txbuffer.copy_from_slice(&data[..DMX_LEN]);
2024-03-21 22:50:21 +00:00
*self = Self::Busy(Some(tx.write(txbuffer)));
2024-03-21 17:58:02 +00:00
}
pub fn wait(&mut self) {
2024-03-21 22:50:21 +00:00
let Self::Busy(xfer) = self else { return };
let xfer = xfer.take().unwrap();
let (txbuffer, tx) = xfer.wait();
2024-03-21 23:35:46 +00:00
*self = Self::Idle(Some(tx), Some(txbuffer));
2024-03-21 14:29:37 +00:00
}
}