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

66 lines
1.8 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
type _TxDma = dma::TxDma<serial::Tx<pac::USART1>, dma::dma1::C4>;
2024-03-21 23:31:59 +00:00
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-21 23:31:59 +00:00
pub struct DMXIdle<const DMX_LEN: usize> {
2024-03-21 17:58:02 +00:00
tx: Option<_TxDma>,
2024-03-21 23:31:59 +00:00
txbuffer: Option<_DMXUniverse<DMX_LEN>>,
2024-03-21 14:29:37 +00:00
}
2024-03-21 23:31:59 +00:00
pub enum DMX<const DMX_LEN: usize = 512> {
Idle(DMXIdle<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-21 19:23:06 +00:00
serial.reconfigure(250_000.bps(), &clocks).unwrap();
2024-03-21 14:29:37 +00:00
2024-03-21 17:58:02 +00:00
Self::Idle(DMXIdle {
2024-03-21 14:29:37 +00:00
tx: Some(serial.tx.with_dma(channel)),
txbuffer: None,
2024-03-21 17:58:02 +00:00
})
2024-03-21 14:29:37 +00:00
}
2024-03-21 23:31:59 +00:00
pub fn send(&mut self, data: &[u8; DMX_LEN]) {
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
let Self::Idle(idle) = self else {
panic!("Broken DMX State!")
};
2024-03-21 23:31:59 +00:00
let txbuffer = idle.txbuffer.take().unwrap_or_else(|| {
let foo = singleton!(: [u8; 512] = [0u8; 512]).unwrap();
(&mut foo[..DMX_LEN]).try_into().unwrap()
});
2024-03-21 22:50:21 +00:00
let tx = idle.tx.take().unwrap();
txbuffer.copy_from_slice(data);
*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();
*self = Self::Idle(DMXIdle {
tx: Some(tx),
txbuffer: Some(txbuffer),
});
2024-03-21 14:29:37 +00:00
}
}