1use core::future::poll_fn;
3use core::marker::PhantomData;
4use core::sync::atomic::{AtomicU16, Ordering};
5use core::task::Poll;
6
7use embassy_futures::select::{Either, select};
8use embassy_hal_internal::{Peri, PeripheralType};
9use embassy_sync::waitqueue::AtomicWaker;
10use embassy_time::{Delay, Timer};
11use pac::uart::regs::Uartris;
12
13use crate::clocks::clk_peri_freq;
14use crate::dma::{Channel, ChannelInstance};
15use crate::gpio::{AnyPin, SealedPin};
16use crate::interrupt::typelevel::{Binding, Interrupt as _};
17use crate::interrupt::{Interrupt, InterruptExt};
18use crate::pac::io::vals::{Inover, Outover};
19use crate::{RegExt, dma, interrupt, pac, peripherals};
20
21mod buffered;
22pub use buffered::{BufferedInterruptHandler, BufferedUart, BufferedUartRx, BufferedUartTx};
23
24#[derive(Clone, Copy, PartialEq, Eq, Debug)]
26pub enum DataBits {
27 DataBits5,
29 DataBits6,
31 DataBits7,
33 DataBits8,
35}
36
37impl DataBits {
38 fn bits(&self) -> u8 {
39 match self {
40 Self::DataBits5 => 0b00,
41 Self::DataBits6 => 0b01,
42 Self::DataBits7 => 0b10,
43 Self::DataBits8 => 0b11,
44 }
45 }
46}
47
48#[derive(Clone, Copy, PartialEq, Eq, Debug)]
50pub enum Parity {
51 ParityNone,
53 ParityEven,
55 ParityOdd,
57}
58
59#[derive(Clone, Copy, PartialEq, Eq, Debug)]
61pub enum StopBits {
62 #[doc = "1 stop bit"]
63 STOP1,
64 #[doc = "2 stop bits"]
65 STOP2,
66}
67
68#[non_exhaustive]
70#[derive(Clone, Copy, PartialEq, Eq, Debug)]
71pub struct Config {
72 pub baudrate: u32,
74 pub data_bits: DataBits,
76 pub stop_bits: StopBits,
78 pub parity: Parity,
80 pub invert_tx: bool,
82 pub invert_rx: bool,
84 pub invert_rts: bool,
86 pub invert_cts: bool,
88}
89
90impl Default for Config {
91 fn default() -> Self {
92 Self {
93 baudrate: 115200,
94 data_bits: DataBits::DataBits8,
95 stop_bits: StopBits::STOP1,
96 parity: Parity::ParityNone,
97 invert_rx: false,
98 invert_tx: false,
99 invert_rts: false,
100 invert_cts: false,
101 }
102 }
103}
104
105#[derive(Debug, Eq, PartialEq, Copy, Clone)]
107#[cfg_attr(feature = "defmt", derive(defmt::Format))]
108#[non_exhaustive]
109pub enum Error {
110 Overrun,
112 Break,
114 Parity,
117 Framing,
119}
120
121impl core::fmt::Display for Error {
122 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
123 core::fmt::Debug::fmt(self, f)
124 }
125}
126
127impl core::error::Error for Error {}
128
129#[derive(Debug, Eq, PartialEq, Copy, Clone)]
131#[cfg_attr(feature = "defmt", derive(defmt::Format))]
132#[non_exhaustive]
133pub enum ReadToBreakError {
134 MissingBreak(usize),
136 Other(Error),
138}
139
140pub struct DmaState {
142 rx_err_waker: AtomicWaker,
143 rx_errs: AtomicU16,
144}
145
146pub struct Uart<'d, M: Mode> {
148 tx: UartTx<'d, M>,
149 rx: UartRx<'d, M>,
150}
151
152pub struct UartTx<'d, M: Mode> {
154 info: &'static Info,
155 tx_dma: Option<dma::Channel<'d>>,
156 phantom: PhantomData<M>,
157}
158
159pub struct UartRx<'d, M: Mode> {
161 info: &'static Info,
162 dma_state: &'static DmaState,
163 rx_dma: Option<dma::Channel<'d>>,
164 phantom: PhantomData<M>,
165}
166
167impl<'d, M: Mode> UartTx<'d, M> {
168 fn new_inner(info: &'static Info, tx_dma: Option<Channel<'d>>) -> Self {
169 Self {
170 info,
171 tx_dma,
172 phantom: PhantomData,
173 }
174 }
175
176 pub fn blocking_write(&mut self, buffer: &[u8]) -> Result<(), Error> {
178 let r = self.info.regs;
179 for &b in buffer {
180 while r.uartfr().read().txff() {}
181 r.uartdr().write(|w| w.set_data(b));
182 }
183 Ok(())
184 }
185
186 pub fn blocking_flush(&mut self) -> Result<(), Error> {
188 while !self.info.regs.uartfr().read().txfe() {}
189 Ok(())
190 }
191
192 pub fn busy(&self) -> bool {
194 self.info.regs.uartfr().read().busy()
195 }
196
197 pub async fn send_break(&mut self, bits: u32) {
205 let regs = self.info.regs;
206 let bits = bits.max({
207 let lcr = regs.uartlcr_h().read();
208 let width = lcr.wlen() as u32 + 5;
209 let parity = lcr.pen() as u32;
210 let stops = 1 + lcr.stp2() as u32;
211 2 * (1 + width + parity + stops)
212 });
213 let divx64 = (((regs.uartibrd().read().baud_divint() as u32) << 6)
214 + regs.uartfbrd().read().baud_divfrac() as u32) as u64;
215 let div_clk = clk_peri_freq() as u64 * 64;
216 let wait_usecs = (1_000_000 * bits as u64 * divx64 * 16 + div_clk - 1) / div_clk;
217
218 self.blocking_flush().unwrap();
219 while self.busy() {}
220 regs.uartlcr_h().write_set(|w| w.set_brk(true));
221 Timer::after_micros(wait_usecs).await;
222 regs.uartlcr_h().write_clear(|w| w.set_brk(true));
223 }
224}
225
226impl<'d> UartTx<'d, Blocking> {
227 pub fn new_blocking<T: Instance>(_uart: Peri<'d, T>, tx: Peri<'d, impl TxPin<T>>, config: Config) -> Self {
229 Uart::<Blocking>::init(T::info(), Some(tx.into()), None, None, None, config);
230 Self::new_inner(T::info(), None)
231 }
232
233 pub fn into_buffered<T: Instance>(
236 self,
237 _irq: impl Binding<T::Interrupt, BufferedInterruptHandler<T>>,
238 tx_buffer: &'d mut [u8],
239 ) -> BufferedUartTx {
240 buffered::init_buffers(T::info(), T::buffered_state(), Some(tx_buffer), None);
241
242 BufferedUartTx {
243 info: T::info(),
244 state: T::buffered_state(),
245 }
246 }
247}
248
249impl<'d> UartTx<'d, Async> {
250 pub fn new<T: Instance, TxDma: ChannelInstance>(
252 _uart: Peri<'d, T>,
253 tx: Peri<'d, impl TxPin<T>>,
254 tx_dma: Peri<'d, TxDma>,
255 irq: impl crate::interrupt::typelevel::Binding<TxDma::Interrupt, crate::dma::InterruptHandler<TxDma>> + 'd,
256 config: Config,
257 ) -> Self {
258 Uart::<Async>::init(T::info(), Some(tx.into()), None, None, None, config);
259 Self::new_inner(T::info(), Some(Channel::new(tx_dma, irq)))
260 }
261
262 pub async fn write(&mut self, buffer: &[u8]) -> Result<(), Error> {
264 let transfer = unsafe {
265 self.info.regs.uartdmacr().write_set(|reg| {
266 reg.set_txdmae(true);
267 });
268 self.tx_dma.as_mut().unwrap().write(
271 buffer,
272 self.info.regs.uartdr().as_ptr() as *mut _,
273 self.info.tx_dreq.into(),
274 false,
275 )
276 };
277 transfer.await;
278 Ok(())
279 }
280}
281
282impl<'d, M: Mode> UartRx<'d, M> {
283 fn new_inner(
284 info: &'static Info,
285 dma_state: &'static DmaState,
286 has_irq: bool,
287 rx_dma: Option<dma::Channel<'d>>,
288 ) -> Self {
289 debug_assert_eq!(has_irq, rx_dma.is_some());
290 if has_irq {
291 info.regs.uartimsc().write(|w| w.0 = 0);
293 info.interrupt.unpend();
294 unsafe { info.interrupt.enable() };
295 }
296 Self {
297 info,
298 dma_state,
299 rx_dma,
300 phantom: PhantomData,
301 }
302 }
303
304 pub fn blocking_read(&mut self, mut buffer: &mut [u8]) -> Result<(), Error> {
306 while !buffer.is_empty() {
307 let received = self.drain_fifo(buffer).map_err(|(_i, e)| e)?;
308 buffer = &mut buffer[received..];
309 }
310 Ok(())
311 }
312
313 fn drain_fifo(&mut self, buffer: &mut [u8]) -> Result<usize, (usize, Error)> {
317 let r = self.info.regs;
318 for (i, b) in buffer.iter_mut().enumerate() {
319 if r.uartfr().read().rxfe() {
320 return Ok(i);
321 }
322
323 let dr = r.uartdr().read();
324
325 if dr.oe() {
326 return Err((i, Error::Overrun));
327 } else if dr.be() {
328 return Err((i, Error::Break));
329 } else if dr.pe() {
330 return Err((i, Error::Parity));
331 } else if dr.fe() {
332 return Err((i, Error::Framing));
333 } else {
334 *b = dr.data();
335 }
336 }
337 Ok(buffer.len())
338 }
339}
340
341impl<'d, M: Mode> Drop for UartRx<'d, M> {
342 fn drop(&mut self) {
343 if self.rx_dma.is_some() {
344 self.info.interrupt.disable();
345 self.info.regs.uartdmacr().write_clear(|reg| {
347 reg.set_rxdmae(true);
348 reg.set_txdmae(true);
349 reg.set_dmaonerr(true);
350 });
351 }
352 }
353}
354
355impl<'d> UartRx<'d, Blocking> {
356 pub fn new_blocking<T: Instance>(_uart: Peri<'d, T>, rx: Peri<'d, impl RxPin<T>>, config: Config) -> Self {
358 Uart::<Blocking>::init(T::info(), None, Some(rx.into()), None, None, config);
359 Self::new_inner(T::info(), T::dma_state(), false, None)
360 }
361
362 pub fn into_buffered<T: Instance>(
365 self,
366 _irq: impl Binding<T::Interrupt, BufferedInterruptHandler<T>>,
367 rx_buffer: &'d mut [u8],
368 ) -> BufferedUartRx {
369 buffered::init_buffers(T::info(), T::buffered_state(), None, Some(rx_buffer));
370
371 BufferedUartRx {
372 info: T::info(),
373 state: T::buffered_state(),
374 }
375 }
376}
377
378pub struct InterruptHandler<T: Instance> {
380 _uart: PhantomData<T>,
381}
382
383impl<T: Instance> interrupt::typelevel::Handler<T::Interrupt> for InterruptHandler<T> {
384 unsafe fn on_interrupt() {
385 let uart = T::info().regs;
386 if !uart.uartdmacr().read().rxdmae() {
387 return;
388 }
389
390 let state = T::dma_state();
391 let errs = uart.uartris().read();
392 state.rx_errs.store(errs.0 as u16, Ordering::Relaxed);
393 state.rx_err_waker.wake();
394 uart.uartimsc().write_clear(|w| w.0 = errs.0);
398 }
399}
400
401impl<'d> UartRx<'d, Async> {
402 pub fn new<T: Instance, RxDma: ChannelInstance>(
404 _uart: Peri<'d, T>,
405 rx: Peri<'d, impl RxPin<T>>,
406 irq: impl Binding<T::Interrupt, InterruptHandler<T>>
407 + crate::interrupt::typelevel::Binding<RxDma::Interrupt, crate::dma::InterruptHandler<RxDma>>
408 + 'd,
409 rx_dma: Peri<'d, RxDma>,
410 config: Config,
411 ) -> Self {
412 Uart::<Async>::init(T::info(), None, Some(rx.into()), None, None, config);
413 Self::new_inner(T::info(), T::dma_state(), true, Some(Channel::new(rx_dma, irq)))
414 }
415
416 pub async fn read(&mut self, buffer: &mut [u8]) -> Result<(), Error> {
418 self.dma_state.rx_errs.store(0, Ordering::Relaxed);
421 self.info.regs.uarticr().write(|w| {
422 w.set_oeic(true);
423 w.set_beic(true);
424 w.set_peic(true);
425 w.set_feic(true);
426 });
427
428 let buffer = match {
431 let limit = buffer.len().min(32);
432 self.drain_fifo(&mut buffer[0..limit])
433 } {
434 Ok(len) if len < buffer.len() => &mut buffer[len..],
435 Ok(_) => return Ok(()),
436 Err((_i, e)) => return Err(e),
437 };
438
439 self.info.regs.uartimsc().write_set(|w| {
443 w.set_oeim(true);
444 w.set_beim(true);
445 w.set_peim(true);
446 w.set_feim(true);
447 });
448 self.info.regs.uartdmacr().write_set(|reg| {
449 reg.set_rxdmae(true);
450 reg.set_dmaonerr(true);
451 });
452 let transfer = unsafe {
453 self.rx_dma.as_mut().unwrap().read(
456 self.info.regs.uartdr().as_ptr() as *const _,
457 buffer,
458 self.info.rx_dreq.into(),
459 false,
460 )
461 };
462
463 let transfer_result = select(
465 transfer,
466 poll_fn(|cx| {
467 self.dma_state.rx_err_waker.register(cx.waker());
468 let rx_errs = critical_section::with(|_| {
469 let val = self.dma_state.rx_errs.load(Ordering::Relaxed);
470 self.dma_state.rx_errs.store(0, Ordering::Relaxed);
471 val
472 });
473 match rx_errs {
474 0 => Poll::Pending,
475 e => Poll::Ready(Uartris(e as u32)),
476 }
477 }),
478 )
479 .await;
480
481 let errors = match transfer_result {
482 Either::First(()) => {
483 Uartris(critical_section::with(|_| {
486 let val = self.dma_state.rx_errs.load(Ordering::Relaxed);
487 self.dma_state.rx_errs.store(0, Ordering::Relaxed);
488 val
489 }) as u32)
490 }
491 Either::Second(e) => {
492 e
495 }
496 };
497
498 if errors.0 == 0 {
500 return Ok(());
501 }
502
503 if errors.oeris() {
505 return Err(Error::Overrun);
506 } else if errors.beris() {
507 return Err(Error::Break);
508 } else if errors.peris() {
509 return Err(Error::Parity);
510 } else if errors.feris() {
511 return Err(Error::Framing);
512 }
513 unreachable!("unrecognized rx error");
514 }
515
516 pub async fn read_to_break(&mut self, buffer: &mut [u8]) -> Result<usize, ReadToBreakError> {
540 self.read_to_break_with_count(buffer, 0).await
541 }
542
543 pub async fn read_to_break_with_count(
569 &mut self,
570 buffer: &mut [u8],
571 min_count: usize,
572 ) -> Result<usize, ReadToBreakError> {
573 self.dma_state.rx_errs.store(0, Ordering::Relaxed);
576 self.info.regs.uarticr().write(|w| {
577 w.set_oeic(true);
578 w.set_beic(true);
579 w.set_peic(true);
580 w.set_feic(true);
581 });
582
583 let mut sbuffer = match {
586 let limit = buffer.len().min(32);
587 self.drain_fifo(&mut buffer[0..limit])
588 } {
589 Ok(len) if len < buffer.len() => &mut buffer[len..],
591 Ok(len) => return Err(ReadToBreakError::MissingBreak(len)),
593 Err((len, Error::Break)) => {
595 if len < min_count && len < buffer.len() {
596 &mut buffer[len..]
597 } else {
598 return Ok(len);
599 }
600 }
601 Err((_i, e)) => return Err(ReadToBreakError::Other(e)),
603 };
604
605 self.info.regs.uartimsc().write_set(|w| {
609 w.set_oeim(true);
610 w.set_beim(true);
611 w.set_peim(true);
612 w.set_feim(true);
613 });
614 self.info.regs.uartdmacr().write_set(|reg| {
615 reg.set_rxdmae(true);
616 reg.set_dmaonerr(true);
617 });
618
619 loop {
620 let transfer = unsafe {
621 self.rx_dma.as_mut().unwrap().read(
624 self.info.regs.uartdr().as_ptr() as *const _,
625 sbuffer,
626 self.info.rx_dreq.into(),
627 false,
628 )
629 };
630
631 let transfer_result = select(
633 transfer,
634 poll_fn(|cx| {
635 self.dma_state.rx_err_waker.register(cx.waker());
636 let rx_errs = critical_section::with(|_| {
637 let val = self.dma_state.rx_errs.load(Ordering::Relaxed);
638 self.dma_state.rx_errs.store(0, Ordering::Relaxed);
639 val
640 });
641 match rx_errs {
642 0 => Poll::Pending,
643 e => Poll::Ready(Uartris(e as u32)),
644 }
645 }),
646 )
647 .await;
648
649 let errors = match transfer_result {
651 Either::First(()) => {
652 Uartris(critical_section::with(|_| {
655 let val = self.dma_state.rx_errs.load(Ordering::Relaxed);
656 self.dma_state.rx_errs.store(0, Ordering::Relaxed);
657 val
658 }) as u32)
659 }
660 Either::Second(e) => {
661 e
664 }
665 };
666
667 if errors.0 == 0 {
668 return Err(ReadToBreakError::MissingBreak(buffer.len()));
671 } else if errors.beris() {
672 let sval = buffer.as_ptr() as usize;
679 let eval = sval + buffer.len();
680
681 let next_addr = self.rx_dma.as_mut().unwrap().write_addr() as usize;
683
684 if (next_addr < sval) || (next_addr > eval) {
689 unreachable!("UART DMA reported invalid `write_addr`");
690 }
691
692 if (next_addr - sval) < min_count {
693 sbuffer = &mut buffer[(next_addr - sval)..];
694 continue;
695 }
696
697 let regs = self.info.regs;
698 let all_full = next_addr == eval;
699
700 let last_was_break = regs.uartrsr().read().be();
708
709 return match (all_full, last_was_break) {
710 (true, true) | (false, _) => {
711 Ok(next_addr.saturating_sub(1 + sval))
714 }
715 (true, false) => {
716 Err(ReadToBreakError::MissingBreak(buffer.len()))
733 }
734 };
735 } else if errors.oeris() {
736 return Err(ReadToBreakError::Other(Error::Overrun));
737 } else if errors.peris() {
738 return Err(ReadToBreakError::Other(Error::Parity));
739 } else if errors.feris() {
740 return Err(ReadToBreakError::Other(Error::Framing));
741 }
742 unreachable!("unrecognized rx error");
743 }
744 }
745}
746
747impl<'d> Uart<'d, Blocking> {
748 pub fn new_blocking<T: Instance>(
750 uart: Peri<'d, T>,
751 tx: Peri<'d, impl TxPin<T>>,
752 rx: Peri<'d, impl RxPin<T>>,
753 config: Config,
754 ) -> Self {
755 Self::new_inner(uart, tx.into(), rx.into(), None, None, false, None, None, config)
756 }
757
758 pub fn new_with_rtscts_blocking<T: Instance>(
760 uart: Peri<'d, T>,
761 tx: Peri<'d, impl TxPin<T>>,
762 rx: Peri<'d, impl RxPin<T>>,
763 rts: Peri<'d, impl RtsPin<T>>,
764 cts: Peri<'d, impl CtsPin<T>>,
765 config: Config,
766 ) -> Self {
767 Self::new_inner(
768 uart,
769 tx.into(),
770 rx.into(),
771 Some(rts.into()),
772 Some(cts.into()),
773 false,
774 None,
775 None,
776 config,
777 )
778 }
779
780 pub fn into_buffered<T: Instance>(
783 self,
784 _irq: impl Binding<T::Interrupt, BufferedInterruptHandler<T>>,
785 tx_buffer: &'d mut [u8],
786 rx_buffer: &'d mut [u8],
787 ) -> BufferedUart {
788 buffered::init_buffers(T::info(), T::buffered_state(), Some(tx_buffer), Some(rx_buffer));
789
790 BufferedUart {
791 rx: BufferedUartRx {
792 info: T::info(),
793 state: T::buffered_state(),
794 },
795 tx: BufferedUartTx {
796 info: T::info(),
797 state: T::buffered_state(),
798 },
799 }
800 }
801}
802
803impl<'d> Uart<'d, Async> {
804 pub fn new<T: Instance, TxDma: ChannelInstance, RxDma: ChannelInstance>(
806 uart: Peri<'d, T>,
807 tx: Peri<'d, impl TxPin<T>>,
808 rx: Peri<'d, impl RxPin<T>>,
809 irq: impl Binding<T::Interrupt, InterruptHandler<T>>
810 + Binding<TxDma::Interrupt, dma::InterruptHandler<TxDma>>
811 + Binding<RxDma::Interrupt, dma::InterruptHandler<RxDma>>
812 + 'd,
813 tx_dma: Peri<'d, TxDma>,
814 rx_dma: Peri<'d, RxDma>,
815 config: Config,
816 ) -> Self {
817 let tx_dma_ch = dma::Channel::new(tx_dma, irq);
818 let rx_dma_ch = dma::Channel::new(rx_dma, irq);
819 Self::new_inner(
820 uart,
821 tx.into(),
822 rx.into(),
823 None,
824 None,
825 true,
826 Some(tx_dma_ch),
827 Some(rx_dma_ch),
828 config,
829 )
830 }
831
832 pub fn new_with_rtscts<T: Instance, TxDma: ChannelInstance, RxDma: ChannelInstance>(
834 uart: Peri<'d, T>,
835 tx: Peri<'d, impl TxPin<T>>,
836 rx: Peri<'d, impl RxPin<T>>,
837 rts: Peri<'d, impl RtsPin<T>>,
838 cts: Peri<'d, impl CtsPin<T>>,
839 irq: impl Binding<T::Interrupt, InterruptHandler<T>>
840 + Binding<TxDma::Interrupt, dma::InterruptHandler<TxDma>>
841 + Binding<RxDma::Interrupt, dma::InterruptHandler<RxDma>>
842 + 'd,
843 tx_dma: Peri<'d, TxDma>,
844 rx_dma: Peri<'d, RxDma>,
845 config: Config,
846 ) -> Self {
847 let tx_dma_ch = dma::Channel::new(tx_dma, irq);
848 let rx_dma_ch = dma::Channel::new(rx_dma, irq);
849 Self::new_inner(
850 uart,
851 tx.into(),
852 rx.into(),
853 Some(rts.into()),
854 Some(cts.into()),
855 true,
856 Some(tx_dma_ch),
857 Some(rx_dma_ch),
858 config,
859 )
860 }
861}
862
863impl<'d, M: Mode> Uart<'d, M> {
864 fn new_inner<T: Instance>(
865 _uart: Peri<'d, T>,
866 mut tx: Peri<'d, AnyPin>,
867 mut rx: Peri<'d, AnyPin>,
868 mut rts: Option<Peri<'d, AnyPin>>,
869 mut cts: Option<Peri<'d, AnyPin>>,
870 has_irq: bool,
871 tx_dma: Option<dma::Channel<'d>>,
872 rx_dma: Option<dma::Channel<'d>>,
873 config: Config,
874 ) -> Self {
875 Self::init(
876 T::info(),
877 Some(tx.reborrow()),
878 Some(rx.reborrow()),
879 rts.as_mut().map(|x| x.reborrow()),
880 cts.as_mut().map(|x| x.reborrow()),
881 config,
882 );
883
884 Self {
885 tx: UartTx::new_inner(T::info(), tx_dma),
886 rx: UartRx::new_inner(T::info(), T::dma_state(), has_irq, rx_dma),
887 }
888 }
889
890 fn init(
891 info: &Info,
892 tx: Option<Peri<'_, AnyPin>>,
893 rx: Option<Peri<'_, AnyPin>>,
894 rts: Option<Peri<'_, AnyPin>>,
895 cts: Option<Peri<'_, AnyPin>>,
896 config: Config,
897 ) {
898 let r = info.regs;
899 if let Some(pin) = &tx {
900 let funcsel = {
901 let pin_number = ((pin.gpio().as_ptr() as u32) & 0x1FF) / 8;
902 if (pin_number % 4) == 0 { 2 } else { 11 }
903 };
904 pin.gpio().ctrl().write(|w| {
905 w.set_funcsel(funcsel);
906 w.set_outover(if config.invert_tx {
907 Outover::INVERT
908 } else {
909 Outover::NORMAL
910 });
911 });
912 pin.pad_ctrl().write(|w| {
913 #[cfg(feature = "_rp235x")]
914 w.set_iso(false);
915 w.set_ie(true);
916 });
917 }
918 if let Some(pin) = &rx {
919 let funcsel = {
920 let pin_number = ((pin.gpio().as_ptr() as u32) & 0x1FF) / 8;
921 if ((pin_number - 1) % 4) == 0 { 2 } else { 11 }
922 };
923 pin.gpio().ctrl().write(|w| {
924 w.set_funcsel(funcsel);
925 w.set_inover(if config.invert_rx {
926 Inover::INVERT
927 } else {
928 Inover::NORMAL
929 });
930 });
931 pin.pad_ctrl().write(|w| {
932 #[cfg(feature = "_rp235x")]
933 w.set_iso(false);
934 w.set_ie(true);
935 });
936 }
937 if let Some(pin) = &cts {
938 pin.gpio().ctrl().write(|w| {
939 w.set_funcsel(2);
940 w.set_inover(if config.invert_cts {
941 Inover::INVERT
942 } else {
943 Inover::NORMAL
944 });
945 });
946 pin.pad_ctrl().write(|w| {
947 #[cfg(feature = "_rp235x")]
948 w.set_iso(false);
949 w.set_ie(true);
950 });
951 }
952 if let Some(pin) = &rts {
953 pin.gpio().ctrl().write(|w| {
954 w.set_funcsel(2);
955 w.set_outover(if config.invert_rts {
956 Outover::INVERT
957 } else {
958 Outover::NORMAL
959 });
960 });
961 pin.pad_ctrl().write(|w| {
962 #[cfg(feature = "_rp235x")]
963 w.set_iso(false);
964 w.set_ie(true);
965 });
966 }
967
968 Self::set_baudrate_inner(info, config.baudrate);
969
970 let (pen, eps) = match config.parity {
971 Parity::ParityNone => (false, false),
972 Parity::ParityOdd => (true, false),
973 Parity::ParityEven => (true, true),
974 };
975
976 r.uartlcr_h().write(|w| {
977 w.set_wlen(config.data_bits.bits());
978 w.set_stp2(config.stop_bits == StopBits::STOP2);
979 w.set_pen(pen);
980 w.set_eps(eps);
981 w.set_fen(true);
982 });
983
984 r.uartifls().write(|w| {
985 w.set_rxiflsel(0b100);
986 w.set_txiflsel(0b000);
987 });
988
989 r.uartcr().write(|w| {
990 w.set_uarten(true);
991 w.set_rxe(true);
992 w.set_txe(true);
993 w.set_ctsen(cts.is_some());
994 w.set_rtsen(rts.is_some());
995 });
996 }
997
998 fn lcr_modify<R>(info: &Info, f: impl FnOnce(&mut crate::pac::uart::regs::UartlcrH) -> R) -> R {
999 let r = info.regs;
1000
1001 let clk_base = crate::clocks::clk_peri_freq();
1022
1023 let cr = r.uartcr().read();
1024 if cr.uarten() {
1025 r.uartcr().modify(|w| {
1026 w.set_uarten(false);
1027 w.set_txe(false);
1028 w.set_rxe(false);
1029 });
1030
1031 let mut brdiv_ratio = 64 * r.uartibrd().read().0 + r.uartfbrd().read().0;
1034 brdiv_ratio <<= 10;
1035 let scaled_freq = clk_base / 3662;
1037 let wait_time_us = brdiv_ratio / scaled_freq;
1038 embedded_hal_1::delay::DelayNs::delay_us(&mut Delay, wait_time_us);
1039 }
1040
1041 let res = r.uartlcr_h().modify(f);
1042
1043 r.uartcr().write_value(cr);
1044
1045 res
1046 }
1047
1048 pub fn set_baudrate(&mut self, baudrate: u32) {
1050 Self::set_baudrate_inner(self.tx.info, baudrate);
1051 }
1052
1053 fn set_baudrate_inner(info: &Info, baudrate: u32) {
1054 let r = info.regs;
1055
1056 let clk_base = crate::clocks::clk_peri_freq();
1057
1058 let baud_rate_div = (8 * clk_base) / baudrate;
1059 let mut baud_ibrd = baud_rate_div >> 7;
1060 let mut baud_fbrd = ((baud_rate_div & 0x7f) + 1) / 2;
1061
1062 if baud_ibrd == 0 {
1063 baud_ibrd = 1;
1064 baud_fbrd = 0;
1065 } else if baud_ibrd >= 65535 {
1066 baud_ibrd = 65535;
1067 baud_fbrd = 0;
1068 }
1069
1070 r.uartibrd().write_value(pac::uart::regs::Uartibrd(baud_ibrd));
1072 r.uartfbrd().write_value(pac::uart::regs::Uartfbrd(baud_fbrd));
1073
1074 Self::lcr_modify(info, |_| {});
1075 }
1076}
1077
1078impl<'d, M: Mode> Uart<'d, M> {
1079 pub fn blocking_write(&mut self, buffer: &[u8]) -> Result<(), Error> {
1081 self.tx.blocking_write(buffer)
1082 }
1083
1084 pub fn blocking_flush(&mut self) -> Result<(), Error> {
1086 self.tx.blocking_flush()
1087 }
1088
1089 pub fn blocking_read(&mut self, buffer: &mut [u8]) -> Result<(), Error> {
1091 self.rx.blocking_read(buffer)
1092 }
1093
1094 pub fn busy(&self) -> bool {
1096 self.tx.busy()
1097 }
1098
1099 pub async fn send_break(&mut self, bits: u32) {
1101 self.tx.send_break(bits).await
1102 }
1103
1104 pub fn split(self) -> (UartTx<'d, M>, UartRx<'d, M>) {
1107 (self.tx, self.rx)
1108 }
1109
1110 pub fn split_ref(&mut self) -> (&mut UartTx<'d, M>, &mut UartRx<'d, M>) {
1114 (&mut self.tx, &mut self.rx)
1115 }
1116}
1117
1118impl<'d> Uart<'d, Async> {
1119 pub async fn write(&mut self, buffer: &[u8]) -> Result<(), Error> {
1121 self.tx.write(buffer).await
1122 }
1123
1124 pub async fn read(&mut self, buffer: &mut [u8]) -> Result<(), Error> {
1126 self.rx.read(buffer).await
1127 }
1128
1129 pub async fn read_to_break<'a>(&mut self, buf: &'a mut [u8]) -> Result<usize, ReadToBreakError> {
1133 self.rx.read_to_break(buf).await
1134 }
1135
1136 pub async fn read_to_break_with_count<'a>(
1140 &mut self,
1141 buf: &'a mut [u8],
1142 min_count: usize,
1143 ) -> Result<usize, ReadToBreakError> {
1144 self.rx.read_to_break_with_count(buf, min_count).await
1145 }
1146}
1147
1148impl<'d, M: Mode> embedded_hal_02::serial::Read<u8> for UartRx<'d, M> {
1149 type Error = Error;
1150 fn read(&mut self) -> Result<u8, nb::Error<Self::Error>> {
1151 let r = self.info.regs;
1152 if r.uartfr().read().rxfe() {
1153 return Err(nb::Error::WouldBlock);
1154 }
1155
1156 let dr = r.uartdr().read();
1157
1158 if dr.oe() {
1159 Err(nb::Error::Other(Error::Overrun))
1160 } else if dr.be() {
1161 Err(nb::Error::Other(Error::Break))
1162 } else if dr.pe() {
1163 Err(nb::Error::Other(Error::Parity))
1164 } else if dr.fe() {
1165 Err(nb::Error::Other(Error::Framing))
1166 } else {
1167 Ok(dr.data())
1168 }
1169 }
1170}
1171
1172impl<'d, M: Mode> embedded_hal_02::serial::Write<u8> for UartTx<'d, M> {
1173 type Error = Error;
1174
1175 fn write(&mut self, word: u8) -> Result<(), nb::Error<Self::Error>> {
1176 let r = self.info.regs;
1177 if r.uartfr().read().txff() {
1178 return Err(nb::Error::WouldBlock);
1179 }
1180
1181 r.uartdr().write(|w| w.set_data(word));
1182 Ok(())
1183 }
1184
1185 fn flush(&mut self) -> Result<(), nb::Error<Self::Error>> {
1186 let r = self.info.regs;
1187 if !r.uartfr().read().txfe() {
1188 return Err(nb::Error::WouldBlock);
1189 }
1190 Ok(())
1191 }
1192}
1193
1194impl<'d, M: Mode> embedded_hal_02::blocking::serial::Write<u8> for UartTx<'d, M> {
1195 type Error = Error;
1196
1197 fn bwrite_all(&mut self, buffer: &[u8]) -> Result<(), Self::Error> {
1198 self.blocking_write(buffer)
1199 }
1200
1201 fn bflush(&mut self) -> Result<(), Self::Error> {
1202 self.blocking_flush()
1203 }
1204}
1205
1206impl<'d, M: Mode> embedded_hal_02::serial::Read<u8> for Uart<'d, M> {
1207 type Error = Error;
1208
1209 fn read(&mut self) -> Result<u8, nb::Error<Self::Error>> {
1210 embedded_hal_02::serial::Read::read(&mut self.rx)
1211 }
1212}
1213
1214impl<'d, M: Mode> embedded_hal_02::serial::Write<u8> for Uart<'d, M> {
1215 type Error = Error;
1216
1217 fn write(&mut self, word: u8) -> Result<(), nb::Error<Self::Error>> {
1218 embedded_hal_02::serial::Write::write(&mut self.tx, word)
1219 }
1220
1221 fn flush(&mut self) -> Result<(), nb::Error<Self::Error>> {
1222 embedded_hal_02::serial::Write::flush(&mut self.tx)
1223 }
1224}
1225
1226impl<'d, M: Mode> embedded_hal_02::blocking::serial::Write<u8> for Uart<'d, M> {
1227 type Error = Error;
1228
1229 fn bwrite_all(&mut self, buffer: &[u8]) -> Result<(), Self::Error> {
1230 self.blocking_write(buffer)
1231 }
1232
1233 fn bflush(&mut self) -> Result<(), Self::Error> {
1234 self.blocking_flush()
1235 }
1236}
1237
1238impl embedded_hal_nb::serial::Error for Error {
1239 fn kind(&self) -> embedded_hal_nb::serial::ErrorKind {
1240 match *self {
1241 Self::Framing => embedded_hal_nb::serial::ErrorKind::FrameFormat,
1242 Self::Break => embedded_hal_nb::serial::ErrorKind::Other,
1243 Self::Overrun => embedded_hal_nb::serial::ErrorKind::Overrun,
1244 Self::Parity => embedded_hal_nb::serial::ErrorKind::Parity,
1245 }
1246 }
1247}
1248
1249impl<'d, M: Mode> embedded_hal_nb::serial::ErrorType for UartRx<'d, M> {
1250 type Error = Error;
1251}
1252
1253impl<'d, M: Mode> embedded_hal_nb::serial::ErrorType for UartTx<'d, M> {
1254 type Error = Error;
1255}
1256
1257impl<'d, M: Mode> embedded_hal_nb::serial::ErrorType for Uart<'d, M> {
1258 type Error = Error;
1259}
1260
1261impl<'d, M: Mode> embedded_hal_nb::serial::Read for UartRx<'d, M> {
1262 fn read(&mut self) -> nb::Result<u8, Self::Error> {
1263 let r = self.info.regs;
1264 if r.uartfr().read().rxfe() {
1265 return Err(nb::Error::WouldBlock);
1266 }
1267
1268 let dr = r.uartdr().read();
1269
1270 if dr.oe() {
1271 Err(nb::Error::Other(Error::Overrun))
1272 } else if dr.be() {
1273 Err(nb::Error::Other(Error::Break))
1274 } else if dr.pe() {
1275 Err(nb::Error::Other(Error::Parity))
1276 } else if dr.fe() {
1277 Err(nb::Error::Other(Error::Framing))
1278 } else {
1279 Ok(dr.data())
1280 }
1281 }
1282}
1283
1284impl<'d, M: Mode> embedded_hal_nb::serial::Write for UartTx<'d, M> {
1285 fn write(&mut self, char: u8) -> nb::Result<(), Self::Error> {
1286 self.blocking_write(&[char]).map_err(nb::Error::Other)
1287 }
1288
1289 fn flush(&mut self) -> nb::Result<(), Self::Error> {
1290 self.blocking_flush().map_err(nb::Error::Other)
1291 }
1292}
1293
1294impl<'d> embedded_io::ErrorType for UartTx<'d, Blocking> {
1295 type Error = Error;
1296}
1297
1298impl<'d> embedded_io::Write for UartTx<'d, Blocking> {
1299 fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
1300 self.blocking_write(buf).map(|_| buf.len())
1301 }
1302
1303 fn flush(&mut self) -> Result<(), Self::Error> {
1304 self.blocking_flush()
1305 }
1306}
1307
1308impl<'d, M: Mode> embedded_hal_nb::serial::Read for Uart<'d, M> {
1309 fn read(&mut self) -> Result<u8, nb::Error<Self::Error>> {
1310 embedded_hal_02::serial::Read::read(&mut self.rx)
1311 }
1312}
1313
1314impl<'d, M: Mode> embedded_hal_nb::serial::Write for Uart<'d, M> {
1315 fn write(&mut self, char: u8) -> nb::Result<(), Self::Error> {
1316 self.blocking_write(&[char]).map_err(nb::Error::Other)
1317 }
1318
1319 fn flush(&mut self) -> nb::Result<(), Self::Error> {
1320 self.blocking_flush().map_err(nb::Error::Other)
1321 }
1322}
1323
1324impl<'d> embedded_io::ErrorType for Uart<'d, Blocking> {
1325 type Error = Error;
1326}
1327
1328impl<'d> embedded_io::Write for Uart<'d, Blocking> {
1329 fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
1330 self.blocking_write(buf).map(|_| buf.len())
1331 }
1332
1333 fn flush(&mut self) -> Result<(), Self::Error> {
1334 self.blocking_flush()
1335 }
1336}
1337
1338struct Info {
1339 regs: pac::uart::Uart,
1340 tx_dreq: pac::dma::vals::TreqSel,
1341 rx_dreq: pac::dma::vals::TreqSel,
1342 interrupt: Interrupt,
1343}
1344
1345trait SealedMode {}
1346
1347trait SealedInstance {
1348 fn info() -> &'static Info;
1349
1350 fn buffered_state() -> &'static buffered::State;
1351
1352 fn dma_state() -> &'static DmaState;
1353}
1354
1355#[allow(private_bounds)]
1357pub trait Mode: SealedMode {}
1358
1359macro_rules! impl_mode {
1360 ($name:ident) => {
1361 impl SealedMode for $name {}
1362 impl Mode for $name {}
1363 };
1364}
1365
1366pub struct Blocking;
1368pub struct Async;
1370
1371impl_mode!(Blocking);
1372impl_mode!(Async);
1373
1374#[allow(private_bounds)]
1376pub trait Instance: SealedInstance + PeripheralType {
1377 type Interrupt: interrupt::typelevel::Interrupt;
1379}
1380
1381macro_rules! impl_instance {
1382 ($inst:ident, $irq:ident, $tx_dreq:expr, $rx_dreq:expr) => {
1383 impl SealedInstance for peripherals::$inst {
1384 fn info() -> &'static Info {
1385 static INFO: Info = Info {
1386 regs: pac::$inst,
1387 tx_dreq: $tx_dreq,
1388 rx_dreq: $rx_dreq,
1389 interrupt: crate::interrupt::typelevel::$irq::IRQ,
1390 };
1391 &INFO
1392 }
1393
1394 fn buffered_state() -> &'static buffered::State {
1395 static STATE: buffered::State = buffered::State::new();
1396 &STATE
1397 }
1398
1399 fn dma_state() -> &'static DmaState {
1400 static STATE: DmaState = DmaState {
1401 rx_err_waker: AtomicWaker::new(),
1402 rx_errs: AtomicU16::new(0),
1403 };
1404 &STATE
1405 }
1406 }
1407 impl Instance for peripherals::$inst {
1408 type Interrupt = crate::interrupt::typelevel::$irq;
1409 }
1410 };
1411}
1412
1413impl_instance!(
1414 UART0,
1415 UART0_IRQ,
1416 pac::dma::vals::TreqSel::UART0_TX,
1417 pac::dma::vals::TreqSel::UART0_RX
1418);
1419impl_instance!(
1420 UART1,
1421 UART1_IRQ,
1422 pac::dma::vals::TreqSel::UART1_TX,
1423 pac::dma::vals::TreqSel::UART1_RX
1424);
1425
1426pub trait TxPin<T: Instance>: crate::gpio::Pin {}
1428pub trait RxPin<T: Instance>: crate::gpio::Pin {}
1430pub trait CtsPin<T: Instance>: crate::gpio::Pin {}
1432pub trait RtsPin<T: Instance>: crate::gpio::Pin {}
1434
1435macro_rules! impl_pin {
1436 ($pin:ident, $instance:ident, $function:ident) => {
1437 impl $function<peripherals::$instance> for peripherals::$pin {}
1438 };
1439}
1440
1441impl_pin!(PIN_0, UART0, TxPin);
1442impl_pin!(PIN_1, UART0, RxPin);
1443impl_pin!(PIN_2, UART0, CtsPin);
1444impl_pin!(PIN_3, UART0, RtsPin);
1445impl_pin!(PIN_4, UART1, TxPin);
1446impl_pin!(PIN_5, UART1, RxPin);
1447impl_pin!(PIN_6, UART1, CtsPin);
1448impl_pin!(PIN_7, UART1, RtsPin);
1449impl_pin!(PIN_8, UART1, TxPin);
1450impl_pin!(PIN_9, UART1, RxPin);
1451impl_pin!(PIN_10, UART1, CtsPin);
1452impl_pin!(PIN_11, UART1, RtsPin);
1453impl_pin!(PIN_12, UART0, TxPin);
1454impl_pin!(PIN_13, UART0, RxPin);
1455impl_pin!(PIN_14, UART0, CtsPin);
1456impl_pin!(PIN_15, UART0, RtsPin);
1457impl_pin!(PIN_16, UART0, TxPin);
1458impl_pin!(PIN_17, UART0, RxPin);
1459impl_pin!(PIN_18, UART0, CtsPin);
1460impl_pin!(PIN_19, UART0, RtsPin);
1461impl_pin!(PIN_20, UART1, TxPin);
1462impl_pin!(PIN_21, UART1, RxPin);
1463impl_pin!(PIN_22, UART1, CtsPin);
1464impl_pin!(PIN_23, UART1, RtsPin);
1465impl_pin!(PIN_24, UART1, TxPin);
1466impl_pin!(PIN_25, UART1, RxPin);
1467impl_pin!(PIN_26, UART1, CtsPin);
1468impl_pin!(PIN_27, UART1, RtsPin);
1469impl_pin!(PIN_28, UART0, TxPin);
1470impl_pin!(PIN_29, UART0, RxPin);
1471
1472#[cfg(feature = "_rp235x")]
1474impl_pin!(PIN_2, UART0, TxPin);
1475#[cfg(feature = "_rp235x")]
1476impl_pin!(PIN_3, UART0, RxPin);
1477#[cfg(feature = "_rp235x")]
1478impl_pin!(PIN_6, UART1, TxPin);
1479#[cfg(feature = "_rp235x")]
1480impl_pin!(PIN_7, UART1, RxPin);
1481#[cfg(feature = "_rp235x")]
1482impl_pin!(PIN_10, UART1, TxPin);
1483#[cfg(feature = "_rp235x")]
1484impl_pin!(PIN_11, UART1, RxPin);
1485#[cfg(feature = "_rp235x")]
1486impl_pin!(PIN_14, UART0, TxPin);
1487#[cfg(feature = "_rp235x")]
1488impl_pin!(PIN_15, UART0, RxPin);
1489#[cfg(feature = "_rp235x")]
1490impl_pin!(PIN_18, UART0, TxPin);
1491#[cfg(feature = "_rp235x")]
1492impl_pin!(PIN_19, UART0, RxPin);
1493#[cfg(feature = "_rp235x")]
1494impl_pin!(PIN_22, UART1, TxPin);
1495#[cfg(feature = "_rp235x")]
1496impl_pin!(PIN_23, UART1, RxPin);
1497#[cfg(feature = "_rp235x")]
1498impl_pin!(PIN_26, UART1, TxPin);
1499#[cfg(feature = "_rp235x")]
1500impl_pin!(PIN_27, UART1, RxPin);
1501
1502#[cfg(feature = "rp235xb")]
1504impl_pin!(PIN_30, UART0, CtsPin);
1505#[cfg(feature = "rp235xb")]
1506impl_pin!(PIN_31, UART0, RtsPin);
1507#[cfg(feature = "rp235xb")]
1508impl_pin!(PIN_32, UART0, TxPin);
1509#[cfg(feature = "rp235xb")]
1510impl_pin!(PIN_33, UART0, RxPin);
1511#[cfg(feature = "rp235xb")]
1512impl_pin!(PIN_34, UART0, CtsPin);
1513#[cfg(feature = "rp235xb")]
1514impl_pin!(PIN_35, UART0, RtsPin);
1515#[cfg(feature = "rp235xb")]
1516impl_pin!(PIN_36, UART1, TxPin);
1517#[cfg(feature = "rp235xb")]
1518impl_pin!(PIN_37, UART1, RxPin);
1519#[cfg(feature = "rp235xb")]
1520impl_pin!(PIN_38, UART1, CtsPin);
1521#[cfg(feature = "rp235xb")]
1522impl_pin!(PIN_39, UART1, RtsPin);
1523#[cfg(feature = "rp235xb")]
1524impl_pin!(PIN_40, UART1, TxPin);
1525#[cfg(feature = "rp235xb")]
1526impl_pin!(PIN_41, UART1, RxPin);
1527#[cfg(feature = "rp235xb")]
1528impl_pin!(PIN_42, UART1, CtsPin);
1529#[cfg(feature = "rp235xb")]
1530impl_pin!(PIN_43, UART1, RtsPin);
1531#[cfg(feature = "rp235xb")]
1532impl_pin!(PIN_44, UART0, TxPin);
1533#[cfg(feature = "rp235xb")]
1534impl_pin!(PIN_45, UART0, RxPin);
1535#[cfg(feature = "rp235xb")]
1536impl_pin!(PIN_46, UART0, CtsPin);
1537#[cfg(feature = "rp235xb")]
1538impl_pin!(PIN_47, UART0, RtsPin);
1539
1540#[cfg(feature = "rp235xb")]
1541impl_pin!(PIN_30, UART0, TxPin);
1542#[cfg(feature = "rp235xb")]
1543impl_pin!(PIN_31, UART0, RxPin);
1544#[cfg(feature = "rp235xb")]
1545impl_pin!(PIN_34, UART0, TxPin);
1546#[cfg(feature = "rp235xb")]
1547impl_pin!(PIN_35, UART0, RxPin);
1548#[cfg(feature = "rp235xb")]
1549impl_pin!(PIN_38, UART1, TxPin);
1550#[cfg(feature = "rp235xb")]
1551impl_pin!(PIN_39, UART1, RxPin);
1552#[cfg(feature = "rp235xb")]
1553impl_pin!(PIN_42, UART1, TxPin);
1554#[cfg(feature = "rp235xb")]
1555impl_pin!(PIN_43, UART1, RxPin);
1556#[cfg(feature = "rp235xb")]
1557impl_pin!(PIN_46, UART0, TxPin);
1558#[cfg(feature = "rp235xb")]
1559impl_pin!(PIN_47, UART0, RxPin);