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

55 lines
1.6 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 enum DMX<const DMX_LEN: usize = 512> {
2024-03-21 23:35:46 +00:00
Idle(Option<_TxDma>, Option<_DMXUniverse<DMX_LEN>>),
2024-03-21 23:31:59 +00:00
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 23:35:46 +00:00
Self::Idle(Some(serial.tx.with_dma(channel)), None)
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
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-21 23:31:59 +00:00
let foo = singleton!(: [u8; 512] = [0u8; 512]).unwrap();
(&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
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();
2024-03-21 23:35:46 +00:00
*self = Self::Idle(Some(tx), Some(txbuffer));
2024-03-21 14:29:37 +00:00
}
}