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 14:29:37 +00:00
|
|
|
|
2024-03-21 17:58:02 +00:00
|
|
|
pub struct DMXIdle {
|
|
|
|
tx: Option<_TxDma>,
|
2024-03-21 14:29:37 +00:00
|
|
|
txbuffer: Option<&'static mut [u8; 512]>,
|
|
|
|
}
|
|
|
|
|
2024-03-21 17:58:02 +00:00
|
|
|
pub enum DMX {
|
|
|
|
Idle(DMXIdle),
|
|
|
|
Busy(Option<dma::Transfer<dma::R, &'static mut [u8; 512], _TxDma>>),
|
|
|
|
}
|
|
|
|
|
2024-03-21 14:29:37 +00:00
|
|
|
impl DMX {
|
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
|
|
|
}
|
|
|
|
|
|
|
|
pub fn send(&mut self, data: &[u8; 512]) {
|
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!")
|
|
|
|
};
|
|
|
|
|
|
|
|
let txbuffer = idle
|
|
|
|
.txbuffer
|
|
|
|
.take()
|
|
|
|
.unwrap_or_else(|| singleton!(: [u8; 512] = [0; 512]).unwrap());
|
|
|
|
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
|
|
|
}
|
|
|
|
}
|