1#![macro_use]
3#![warn(missing_docs)]
4
5use core::future::poll_fn;
6use core::marker::PhantomData;
7use core::sync::atomic::{compiler_fence, AtomicU8, Ordering};
8use core::task::Poll;
9
10use embassy_embedded_hal::SetConfig;
11use embassy_hal_internal::drop::OnDrop;
12use embassy_hal_internal::PeripheralType;
13use embassy_sync::waitqueue::AtomicWaker;
14use futures_util::future::{select, Either};
15
16use crate::dma::ChannelAndRequest;
17use crate::gpio::{AfType, AnyPin, OutputType, Pull, SealedPin as _, Speed};
18use crate::interrupt::typelevel::Interrupt as _;
19use crate::interrupt::{self, Interrupt, InterruptExt};
20use crate::mode::{Async, Blocking, Mode};
21#[cfg(not(any(usart_v1, usart_v2)))]
22use crate::pac::usart::Lpuart as Regs;
23#[cfg(any(usart_v1, usart_v2))]
24use crate::pac::usart::Usart as Regs;
25use crate::pac::usart::{regs, vals};
26use crate::rcc::{RccInfo, SealedRccPeripheral};
27use crate::time::Hertz;
28use crate::Peri;
29
30pub struct InterruptHandler<T: Instance> {
32 _phantom: PhantomData<T>,
33}
34
35impl<T: Instance> interrupt::typelevel::Handler<T::Interrupt> for InterruptHandler<T> {
36 unsafe fn on_interrupt() {
37 on_interrupt(T::info().regs, T::state())
38 }
39}
40
41unsafe fn on_interrupt(r: Regs, s: &'static State) {
42 let (sr, cr1, cr3) = (sr(r).read(), r.cr1().read(), r.cr3().read());
43
44 let has_errors = (sr.pe() && cr1.peie()) || ((sr.fe() || sr.ne() || sr.ore()) && cr3.eie());
45 if has_errors {
46 r.cr1().modify(|w| {
48 w.set_rxneie(false);
50 w.set_peie(false);
52 w.set_idleie(false);
54 });
55 r.cr3().modify(|w| {
56 w.set_eie(false);
58 w.set_dmar(false);
60 });
61 } else if cr1.idleie() && sr.idle() {
62 r.cr1().modify(|w| {
64 w.set_idleie(false);
66 });
67 } else if cr1.tcie() && sr.tc() {
68 r.cr1().modify(|w| {
70 w.set_tcie(false);
72 });
73 } else if cr1.rxneie() {
74 } else {
78 return;
79 }
80
81 compiler_fence(Ordering::SeqCst);
82 s.rx_waker.wake();
83 s.tx_waker.wake();
84}
85
86#[derive(Clone, Copy, PartialEq, Eq, Debug)]
87#[cfg_attr(feature = "defmt", derive(defmt::Format))]
88pub enum DataBits {
90 DataBits7,
92 DataBits8,
94 DataBits9,
96}
97
98#[derive(Clone, Copy, PartialEq, Eq, Debug)]
99#[cfg_attr(feature = "defmt", derive(defmt::Format))]
100pub enum Parity {
102 ParityNone,
104 ParityEven,
106 ParityOdd,
108}
109
110#[derive(Clone, Copy, PartialEq, Eq, Debug)]
111#[cfg_attr(feature = "defmt", derive(defmt::Format))]
112pub enum StopBits {
114 #[doc = "1 stop bit"]
115 STOP1,
116 #[doc = "0.5 stop bits"]
117 STOP0P5,
118 #[doc = "2 stop bits"]
119 STOP2,
120 #[doc = "1.5 stop bits"]
121 STOP1P5,
122}
123
124#[derive(Clone, Copy, PartialEq, Eq, Debug)]
125#[cfg_attr(feature = "defmt", derive(defmt::Format))]
126pub enum HalfDuplexReadback {
128 NoReadback,
130 Readback,
132}
133
134#[derive(Clone, Copy, PartialEq, Eq, Debug)]
135#[cfg_attr(feature = "defmt", derive(defmt::Format))]
136pub enum OutputConfig {
138 PushPull,
140 OpenDrain,
142 #[cfg(not(gpio_v1))]
143 OpenDrainPullUp,
145}
146
147impl OutputConfig {
148 const fn af_type(self) -> AfType {
149 match self {
150 OutputConfig::PushPull => AfType::output(OutputType::PushPull, Speed::Medium),
151 OutputConfig::OpenDrain => AfType::output(OutputType::OpenDrain, Speed::Medium),
152 #[cfg(not(gpio_v1))]
153 OutputConfig::OpenDrainPullUp => AfType::output_pull(OutputType::OpenDrain, Speed::Medium, Pull::Up),
154 }
155 }
156}
157
158#[derive(Clone, Copy, PartialEq, Eq, Debug)]
159#[cfg_attr(feature = "defmt", derive(defmt::Format))]
160pub enum Duplex {
162 Full,
164 Half(HalfDuplexReadback),
166}
167
168impl Duplex {
169 fn is_half(&self) -> bool {
171 matches!(self, Duplex::Half(_))
172 }
173}
174
175#[non_exhaustive]
176#[derive(Clone, Copy, PartialEq, Eq, Debug)]
177#[cfg_attr(feature = "defmt", derive(defmt::Format))]
178pub enum ConfigError {
180 BaudrateTooLow,
182 BaudrateTooHigh,
184 RxOrTxNotEnabled,
186 DataParityNotSupported,
188}
189
190#[non_exhaustive]
191#[derive(Clone, Copy, PartialEq, Eq, Debug)]
192pub struct Config {
194 pub baudrate: u32,
196 pub data_bits: DataBits,
198 pub stop_bits: StopBits,
200 pub parity: Parity,
202
203 pub detect_previous_overrun: bool,
208
209 #[cfg(not(usart_v1))]
213 pub assume_noise_free: bool,
214
215 #[cfg(any(usart_v3, usart_v4))]
217 pub swap_rx_tx: bool,
218
219 #[cfg(any(usart_v3, usart_v4))]
221 pub invert_tx: bool,
222
223 #[cfg(any(usart_v3, usart_v4))]
225 pub invert_rx: bool,
226
227 pub rx_pull: Pull,
229
230 pub cts_pull: Pull,
232
233 pub tx_config: OutputConfig,
235
236 pub rts_config: OutputConfig,
238
239 pub de_config: OutputConfig,
241
242 duplex: Duplex,
244}
245
246impl Config {
247 fn tx_af(&self) -> AfType {
248 #[cfg(any(usart_v3, usart_v4))]
249 if self.swap_rx_tx {
250 return AfType::input(self.rx_pull);
251 };
252 self.tx_config.af_type()
253 }
254
255 fn rx_af(&self) -> AfType {
256 #[cfg(any(usart_v3, usart_v4))]
257 if self.swap_rx_tx {
258 return self.tx_config.af_type();
259 };
260 AfType::input(self.rx_pull)
261 }
262}
263
264impl Default for Config {
265 fn default() -> Self {
266 Self {
267 baudrate: 115200,
268 data_bits: DataBits::DataBits8,
269 stop_bits: StopBits::STOP1,
270 parity: Parity::ParityNone,
271 detect_previous_overrun: false,
273 #[cfg(not(usart_v1))]
274 assume_noise_free: false,
275 #[cfg(any(usart_v3, usart_v4))]
276 swap_rx_tx: false,
277 #[cfg(any(usart_v3, usart_v4))]
278 invert_tx: false,
279 #[cfg(any(usart_v3, usart_v4))]
280 invert_rx: false,
281 rx_pull: Pull::None,
282 cts_pull: Pull::None,
283 tx_config: OutputConfig::PushPull,
284 rts_config: OutputConfig::PushPull,
285 de_config: OutputConfig::PushPull,
286 duplex: Duplex::Full,
287 }
288 }
289}
290
291#[derive(Debug, Eq, PartialEq, Copy, Clone)]
293#[cfg_attr(feature = "defmt", derive(defmt::Format))]
294#[non_exhaustive]
295pub enum Error {
296 Framing,
298 Noise,
300 Overrun,
302 Parity,
304 BufferTooLong,
306}
307
308impl core::fmt::Display for Error {
309 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
310 let message = match self {
311 Self::Framing => "Framing Error",
312 Self::Noise => "Noise Error",
313 Self::Overrun => "RX Buffer Overrun",
314 Self::Parity => "Parity Check Error",
315 Self::BufferTooLong => "Buffer too large for DMA",
316 };
317
318 write!(f, "{}", message)
319 }
320}
321
322impl core::error::Error for Error {}
323
324enum ReadCompletionEvent {
325 DmaCompleted,
327 Idle(usize),
329}
330
331pub struct Uart<'d, M: Mode> {
340 tx: UartTx<'d, M>,
341 rx: UartRx<'d, M>,
342}
343
344impl<'d, M: Mode> SetConfig for Uart<'d, M> {
345 type Config = Config;
346 type ConfigError = ConfigError;
347
348 fn set_config(&mut self, config: &Self::Config) -> Result<(), Self::ConfigError> {
349 self.tx.set_config(config)?;
350 self.rx.set_config(config)
351 }
352}
353
354pub struct UartTx<'d, M: Mode> {
359 info: &'static Info,
360 state: &'static State,
361 kernel_clock: Hertz,
362 tx: Option<Peri<'d, AnyPin>>,
363 cts: Option<Peri<'d, AnyPin>>,
364 de: Option<Peri<'d, AnyPin>>,
365 tx_dma: Option<ChannelAndRequest<'d>>,
366 duplex: Duplex,
367 _phantom: PhantomData<M>,
368}
369
370impl<'d, M: Mode> SetConfig for UartTx<'d, M> {
371 type Config = Config;
372 type ConfigError = ConfigError;
373
374 fn set_config(&mut self, config: &Self::Config) -> Result<(), Self::ConfigError> {
375 self.set_config(config)
376 }
377}
378
379pub struct UartRx<'d, M: Mode> {
409 info: &'static Info,
410 state: &'static State,
411 kernel_clock: Hertz,
412 rx: Option<Peri<'d, AnyPin>>,
413 rts: Option<Peri<'d, AnyPin>>,
414 rx_dma: Option<ChannelAndRequest<'d>>,
415 detect_previous_overrun: bool,
416 #[cfg(any(usart_v1, usart_v2))]
417 buffered_sr: regs::Sr,
418 _phantom: PhantomData<M>,
419}
420
421impl<'d, M: Mode> SetConfig for UartRx<'d, M> {
422 type Config = Config;
423 type ConfigError = ConfigError;
424
425 fn set_config(&mut self, config: &Self::Config) -> Result<(), Self::ConfigError> {
426 self.set_config(config)
427 }
428}
429
430impl<'d> UartTx<'d, Async> {
431 pub fn new<T: Instance>(
433 peri: Peri<'d, T>,
434 tx: Peri<'d, impl TxPin<T>>,
435 tx_dma: Peri<'d, impl TxDma<T>>,
436 config: Config,
437 ) -> Result<Self, ConfigError> {
438 Self::new_inner(peri, new_pin!(tx, config.tx_af()), None, new_dma!(tx_dma), config)
439 }
440
441 pub fn new_with_cts<T: Instance>(
443 peri: Peri<'d, T>,
444 tx: Peri<'d, impl TxPin<T>>,
445 cts: Peri<'d, impl CtsPin<T>>,
446 tx_dma: Peri<'d, impl TxDma<T>>,
447 config: Config,
448 ) -> Result<Self, ConfigError> {
449 Self::new_inner(
450 peri,
451 new_pin!(tx, config.tx_af()),
452 new_pin!(cts, AfType::input(config.cts_pull)),
453 new_dma!(tx_dma),
454 config,
455 )
456 }
457
458 pub async fn write(&mut self, buffer: &[u8]) -> Result<(), Error> {
460 let r = self.info.regs;
461
462 half_duplex_set_rx_tx_before_write(&r, self.duplex == Duplex::Half(HalfDuplexReadback::Readback));
463
464 let ch = self.tx_dma.as_mut().unwrap();
465 r.cr3().modify(|reg| {
466 reg.set_dmat(true);
467 });
468 let transfer = unsafe { ch.write(buffer, tdr(r), Default::default()) };
471 transfer.await;
472 Ok(())
473 }
474
475 pub async fn flush(&mut self) -> Result<(), Error> {
477 flush(&self.info, &self.state).await
478 }
479}
480
481impl<'d> UartTx<'d, Blocking> {
482 pub fn new_blocking<T: Instance>(
486 peri: Peri<'d, T>,
487 tx: Peri<'d, impl TxPin<T>>,
488 config: Config,
489 ) -> Result<Self, ConfigError> {
490 Self::new_inner(peri, new_pin!(tx, config.tx_af()), None, None, config)
491 }
492
493 pub fn new_blocking_with_cts<T: Instance>(
495 peri: Peri<'d, T>,
496 tx: Peri<'d, impl TxPin<T>>,
497 cts: Peri<'d, impl CtsPin<T>>,
498 config: Config,
499 ) -> Result<Self, ConfigError> {
500 Self::new_inner(
501 peri,
502 new_pin!(tx, config.tx_af()),
503 new_pin!(cts, AfType::input(config.cts_pull)),
504 None,
505 config,
506 )
507 }
508}
509
510impl<'d, M: Mode> UartTx<'d, M> {
511 fn new_inner<T: Instance>(
512 _peri: Peri<'d, T>,
513 tx: Option<Peri<'d, AnyPin>>,
514 cts: Option<Peri<'d, AnyPin>>,
515 tx_dma: Option<ChannelAndRequest<'d>>,
516 config: Config,
517 ) -> Result<Self, ConfigError> {
518 let mut this = Self {
519 info: T::info(),
520 state: T::state(),
521 kernel_clock: T::frequency(),
522 tx,
523 cts,
524 de: None,
525 tx_dma,
526 duplex: config.duplex,
527 _phantom: PhantomData,
528 };
529 this.enable_and_configure(&config)?;
530 Ok(this)
531 }
532
533 fn enable_and_configure(&mut self, config: &Config) -> Result<(), ConfigError> {
534 let info = self.info;
535 let state = self.state;
536 state.tx_rx_refcount.store(1, Ordering::Relaxed);
537
538 info.rcc.enable_and_reset();
539
540 info.regs.cr3().modify(|w| {
541 w.set_ctse(self.cts.is_some());
542 });
543 configure(info, self.kernel_clock, config, false, true)?;
544
545 Ok(())
546 }
547
548 pub fn set_config(&mut self, config: &Config) -> Result<(), ConfigError> {
550 reconfigure(self.info, self.kernel_clock, config)
551 }
552
553 pub(crate) fn nb_write(&mut self, byte: u8) -> Result<(), nb::Error<Error>> {
555 let r = self.info.regs;
556 let sr = sr(r).read();
557 if sr.txe() {
558 unsafe {
559 tdr(r).write_volatile(byte);
560 }
561 Ok(())
562 } else {
563 Err(nb::Error::WouldBlock)
564 }
565 }
566
567 pub fn blocking_write(&mut self, buffer: &[u8]) -> Result<(), Error> {
569 let r = self.info.regs;
570
571 half_duplex_set_rx_tx_before_write(&r, self.duplex == Duplex::Half(HalfDuplexReadback::Readback));
572
573 for &b in buffer {
574 while !sr(r).read().txe() {}
575 unsafe { tdr(r).write_volatile(b) };
576 }
577 Ok(())
578 }
579
580 pub fn blocking_flush(&mut self) -> Result<(), Error> {
582 blocking_flush(self.info)
583 }
584
585 pub fn send_break(&self) {
587 send_break(&self.info.regs);
588 }
589
590 pub fn set_baudrate(&self, baudrate: u32) -> Result<(), ConfigError> {
592 set_baudrate(self.info, self.kernel_clock, baudrate)
593 }
594}
595
596async fn flush(info: &Info, state: &State) -> Result<(), Error> {
598 let r = info.regs;
599 if r.cr1().read().te() && !sr(r).read().tc() {
600 r.cr1().modify(|w| {
601 w.set_tcie(true);
603 });
604
605 compiler_fence(Ordering::SeqCst);
606
607 let abort = poll_fn(move |cx| {
609 state.tx_waker.register(cx.waker());
610
611 let sr = sr(r).read();
612 if sr.tc() {
613 return Poll::Ready(());
615 }
616
617 Poll::Pending
618 });
619
620 abort.await;
621 }
622
623 Ok(())
624}
625
626fn blocking_flush(info: &Info) -> Result<(), Error> {
627 let r = info.regs;
628 if r.cr1().read().te() {
629 while !sr(r).read().tc() {}
630 }
631
632 Ok(())
633}
634
635pub fn send_break(regs: &Regs) {
637 #[cfg(any(usart_v1, usart_v2))]
639 while regs.cr1().read().sbk() {}
640 #[cfg(any(usart_v3, usart_v4))]
641 while regs.isr().read().sbkf() {}
642
643 #[cfg(any(usart_v1, usart_v2))]
645 regs.cr1().modify(|w| w.set_sbk(true));
646 #[cfg(any(usart_v3, usart_v4))]
647 regs.rqr().write(|w| w.set_sbkrq(true));
648}
649
650fn half_duplex_set_rx_tx_before_write(r: &Regs, enable_readback: bool) {
653 let mut cr1 = r.cr1().read();
654 if r.cr3().read().hdsel() {
655 cr1.set_te(true);
656 cr1.set_re(enable_readback);
657 r.cr1().write_value(cr1);
658 }
659}
660
661impl<'d> UartRx<'d, Async> {
662 pub fn new<T: Instance>(
666 peri: Peri<'d, T>,
667 _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
668 rx: Peri<'d, impl RxPin<T>>,
669 rx_dma: Peri<'d, impl RxDma<T>>,
670 config: Config,
671 ) -> Result<Self, ConfigError> {
672 Self::new_inner(peri, new_pin!(rx, config.rx_af()), None, new_dma!(rx_dma), config)
673 }
674
675 pub fn new_with_rts<T: Instance>(
677 peri: Peri<'d, T>,
678 _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
679 rx: Peri<'d, impl RxPin<T>>,
680 rts: Peri<'d, impl RtsPin<T>>,
681 rx_dma: Peri<'d, impl RxDma<T>>,
682 config: Config,
683 ) -> Result<Self, ConfigError> {
684 Self::new_inner(
685 peri,
686 new_pin!(rx, config.rx_af()),
687 new_pin!(rts, config.rts_config.af_type()),
688 new_dma!(rx_dma),
689 config,
690 )
691 }
692
693 pub async fn read(&mut self, buffer: &mut [u8]) -> Result<(), Error> {
695 self.inner_read(buffer, false).await?;
696
697 Ok(())
698 }
699
700 pub async fn read_until_idle(&mut self, buffer: &mut [u8]) -> Result<usize, Error> {
702 self.inner_read(buffer, true).await
703 }
704
705 async fn inner_read_run(
706 &mut self,
707 buffer: &mut [u8],
708 enable_idle_line_detection: bool,
709 ) -> Result<ReadCompletionEvent, Error> {
710 let r = self.info.regs;
711
712 if r.cr3().read().hdsel() && r.cr1().read().te() {
715 flush(&self.info, &self.state).await?;
716
717 r.cr1().modify(|reg| {
719 reg.set_re(true);
720 reg.set_te(false);
721 });
722 }
723
724 let on_drop = OnDrop::new(move || {
726 r.cr1().modify(|w| {
728 w.set_rxneie(false);
730 w.set_peie(false);
732 w.set_idleie(false);
734 });
735 r.cr3().modify(|w| {
736 w.set_eie(false);
738 w.set_dmar(false);
740 });
741 });
742
743 let ch = self.rx_dma.as_mut().unwrap();
744
745 let buffer_len = buffer.len();
746
747 let transfer = unsafe { ch.read(rdr(r), buffer, Default::default()) };
751
752 if !self.detect_previous_overrun {
754 let sr = sr(r).read();
755 unsafe { rdr(r).read_volatile() };
757 clear_interrupt_flags(r, sr);
758 }
759
760 r.cr1().modify(|w| {
761 w.set_rxneie(false);
763 w.set_peie(w.pce());
765 });
766
767 r.cr3().modify(|w| {
768 w.set_eie(true);
770 w.set_dmar(true);
772 });
773
774 compiler_fence(Ordering::SeqCst);
775
776 let cr3 = r.cr3().read();
781
782 if !cr3.dmar() {
783 let sr = sr(r).read();
789 unsafe { rdr(r).read_volatile() };
791 clear_interrupt_flags(r, sr);
792
793 if sr.pe() {
794 return Err(Error::Parity);
795 }
796 if sr.fe() {
797 return Err(Error::Framing);
798 }
799 if sr.ne() {
800 return Err(Error::Noise);
801 }
802 if sr.ore() {
803 return Err(Error::Overrun);
804 }
805
806 unreachable!();
807 }
808
809 if enable_idle_line_detection {
810 let sr = sr(r).read();
812 unsafe { rdr(r).read_volatile() };
814 clear_interrupt_flags(r, sr);
815
816 r.cr1().modify(|w| {
818 w.set_idleie(true);
819 });
820 }
821
822 compiler_fence(Ordering::SeqCst);
823
824 let s = self.state;
826 let abort = poll_fn(move |cx| {
827 s.rx_waker.register(cx.waker());
828
829 let sr = sr(r).read();
830
831 unsafe { rdr(r).read_volatile() };
833 clear_interrupt_flags(r, sr);
834
835 if enable_idle_line_detection {
836 r.cr1().modify(|w| {
838 w.set_idleie(true);
839 });
840 }
841
842 compiler_fence(Ordering::SeqCst);
843
844 let has_errors = sr.pe() || sr.fe() || sr.ne() || sr.ore();
845
846 if has_errors {
847 if sr.pe() {
850 return Poll::Ready(Err(Error::Parity));
851 }
852 if sr.fe() {
853 return Poll::Ready(Err(Error::Framing));
854 }
855 if sr.ne() {
856 return Poll::Ready(Err(Error::Noise));
857 }
858 if sr.ore() {
859 return Poll::Ready(Err(Error::Overrun));
860 }
861 }
862
863 if enable_idle_line_detection && sr.idle() {
864 return Poll::Ready(Ok(()));
866 }
867
868 Poll::Pending
869 });
870
871 let r = match select(transfer, abort).await {
875 Either::Left(((), _)) => Ok(ReadCompletionEvent::DmaCompleted),
877
878 Either::Right((Ok(()), transfer)) => Ok(ReadCompletionEvent::Idle(
880 buffer_len - transfer.get_remaining_transfers() as usize,
881 )),
882
883 Either::Right((Err(e), _)) => Err(e),
885 };
886
887 drop(on_drop);
888
889 r
890 }
891
892 async fn inner_read(&mut self, buffer: &mut [u8], enable_idle_line_detection: bool) -> Result<usize, Error> {
893 if buffer.is_empty() {
894 return Ok(0);
895 } else if buffer.len() > 0xFFFF {
896 return Err(Error::BufferTooLong);
897 }
898
899 let buffer_len = buffer.len();
900
901 let res = self.inner_read_run(buffer, enable_idle_line_detection).await;
903
904 match res {
905 Ok(ReadCompletionEvent::DmaCompleted) => Ok(buffer_len),
906 Ok(ReadCompletionEvent::Idle(n)) => Ok(n),
907 Err(e) => Err(e),
908 }
909 }
910}
911
912impl<'d> UartRx<'d, Blocking> {
913 pub fn new_blocking<T: Instance>(
917 peri: Peri<'d, T>,
918 rx: Peri<'d, impl RxPin<T>>,
919 config: Config,
920 ) -> Result<Self, ConfigError> {
921 Self::new_inner(peri, new_pin!(rx, config.rx_af()), None, None, config)
922 }
923
924 pub fn new_blocking_with_rts<T: Instance>(
926 peri: Peri<'d, T>,
927 rx: Peri<'d, impl RxPin<T>>,
928 rts: Peri<'d, impl RtsPin<T>>,
929 config: Config,
930 ) -> Result<Self, ConfigError> {
931 Self::new_inner(
932 peri,
933 new_pin!(rx, config.rx_af()),
934 new_pin!(rts, config.rts_config.af_type()),
935 None,
936 config,
937 )
938 }
939}
940
941impl<'d, M: Mode> UartRx<'d, M> {
942 fn new_inner<T: Instance>(
943 _peri: Peri<'d, T>,
944 rx: Option<Peri<'d, AnyPin>>,
945 rts: Option<Peri<'d, AnyPin>>,
946 rx_dma: Option<ChannelAndRequest<'d>>,
947 config: Config,
948 ) -> Result<Self, ConfigError> {
949 let mut this = Self {
950 _phantom: PhantomData,
951 info: T::info(),
952 state: T::state(),
953 kernel_clock: T::frequency(),
954 rx,
955 rts,
956 rx_dma,
957 detect_previous_overrun: config.detect_previous_overrun,
958 #[cfg(any(usart_v1, usart_v2))]
959 buffered_sr: regs::Sr(0),
960 };
961 this.enable_and_configure(&config)?;
962 Ok(this)
963 }
964
965 fn enable_and_configure(&mut self, config: &Config) -> Result<(), ConfigError> {
966 let info = self.info;
967 let state = self.state;
968 state.tx_rx_refcount.store(1, Ordering::Relaxed);
969
970 info.rcc.enable_and_reset();
971
972 info.regs.cr3().write(|w| {
973 w.set_rtse(self.rts.is_some());
974 });
975 configure(info, self.kernel_clock, &config, true, false)?;
976
977 info.interrupt.unpend();
978 unsafe { info.interrupt.enable() };
979
980 Ok(())
981 }
982
983 pub fn set_config(&mut self, config: &Config) -> Result<(), ConfigError> {
985 reconfigure(self.info, self.kernel_clock, config)
986 }
987
988 #[cfg(any(usart_v1, usart_v2))]
989 fn check_rx_flags(&mut self) -> Result<bool, Error> {
990 let r = self.info.regs;
991 loop {
992 if self.buffered_sr.pe() {
994 self.buffered_sr.set_pe(false);
995 return Err(Error::Parity);
996 } else if self.buffered_sr.fe() {
997 self.buffered_sr.set_fe(false);
998 return Err(Error::Framing);
999 } else if self.buffered_sr.ne() {
1000 self.buffered_sr.set_ne(false);
1001 return Err(Error::Noise);
1002 } else if self.buffered_sr.ore() {
1003 self.buffered_sr.set_ore(false);
1004 return Err(Error::Overrun);
1005 } else if self.buffered_sr.rxne() {
1006 self.buffered_sr.set_rxne(false);
1007 return Ok(true);
1008 } else {
1009 let sr = r.sr().read();
1011 if !sr.rxne() {
1012 return Ok(false);
1013 }
1014
1015 self.buffered_sr = sr;
1017 }
1018 }
1019 }
1020
1021 #[cfg(any(usart_v3, usart_v4))]
1022 fn check_rx_flags(&mut self) -> Result<bool, Error> {
1023 let r = self.info.regs;
1024 let sr = r.isr().read();
1025 if sr.pe() {
1026 r.icr().write(|w| w.set_pe(true));
1027 return Err(Error::Parity);
1028 } else if sr.fe() {
1029 r.icr().write(|w| w.set_fe(true));
1030 return Err(Error::Framing);
1031 } else if sr.ne() {
1032 r.icr().write(|w| w.set_ne(true));
1033 return Err(Error::Noise);
1034 } else if sr.ore() {
1035 r.icr().write(|w| w.set_ore(true));
1036 return Err(Error::Overrun);
1037 }
1038 Ok(sr.rxne())
1039 }
1040
1041 pub(crate) fn nb_read(&mut self) -> Result<u8, nb::Error<Error>> {
1043 let r = self.info.regs;
1044 if self.check_rx_flags()? {
1045 Ok(unsafe { rdr(r).read_volatile() })
1046 } else {
1047 Err(nb::Error::WouldBlock)
1048 }
1049 }
1050
1051 pub fn blocking_read(&mut self, buffer: &mut [u8]) -> Result<(), Error> {
1053 let r = self.info.regs;
1054
1055 if r.cr3().read().hdsel() && r.cr1().read().te() {
1058 blocking_flush(self.info)?;
1059
1060 r.cr1().modify(|reg| {
1062 reg.set_re(true);
1063 reg.set_te(false);
1064 });
1065 }
1066
1067 for b in buffer {
1068 while !self.check_rx_flags()? {}
1069 unsafe { *b = rdr(r).read_volatile() }
1070 }
1071 Ok(())
1072 }
1073
1074 pub fn set_baudrate(&self, baudrate: u32) -> Result<(), ConfigError> {
1076 set_baudrate(self.info, self.kernel_clock, baudrate)
1077 }
1078}
1079
1080impl<'d, M: Mode> Drop for UartTx<'d, M> {
1081 fn drop(&mut self) {
1082 self.tx.as_ref().map(|x| x.set_as_disconnected());
1083 self.cts.as_ref().map(|x| x.set_as_disconnected());
1084 self.de.as_ref().map(|x| x.set_as_disconnected());
1085 drop_tx_rx(self.info, self.state);
1086 }
1087}
1088
1089impl<'d, M: Mode> Drop for UartRx<'d, M> {
1090 fn drop(&mut self) {
1091 self.rx.as_ref().map(|x| x.set_as_disconnected());
1092 self.rts.as_ref().map(|x| x.set_as_disconnected());
1093 drop_tx_rx(self.info, self.state);
1094 }
1095}
1096
1097fn drop_tx_rx(info: &Info, state: &State) {
1098 let is_last_drop = critical_section::with(|_| {
1100 let refcount = state.tx_rx_refcount.load(Ordering::Relaxed);
1101 assert!(refcount >= 1);
1102 state.tx_rx_refcount.store(refcount - 1, Ordering::Relaxed);
1103 refcount == 1
1104 });
1105 if is_last_drop {
1106 info.rcc.disable();
1107 }
1108}
1109
1110impl<'d> Uart<'d, Async> {
1111 pub fn new<T: Instance>(
1113 peri: Peri<'d, T>,
1114 rx: Peri<'d, impl RxPin<T>>,
1115 tx: Peri<'d, impl TxPin<T>>,
1116 _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
1117 tx_dma: Peri<'d, impl TxDma<T>>,
1118 rx_dma: Peri<'d, impl RxDma<T>>,
1119 config: Config,
1120 ) -> Result<Self, ConfigError> {
1121 Self::new_inner(
1122 peri,
1123 new_pin!(rx, config.rx_af()),
1124 new_pin!(tx, config.tx_af()),
1125 None,
1126 None,
1127 None,
1128 new_dma!(tx_dma),
1129 new_dma!(rx_dma),
1130 config,
1131 )
1132 }
1133
1134 pub fn new_with_rtscts<T: Instance>(
1136 peri: Peri<'d, T>,
1137 rx: Peri<'d, impl RxPin<T>>,
1138 tx: Peri<'d, impl TxPin<T>>,
1139 _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
1140 rts: Peri<'d, impl RtsPin<T>>,
1141 cts: Peri<'d, impl CtsPin<T>>,
1142 tx_dma: Peri<'d, impl TxDma<T>>,
1143 rx_dma: Peri<'d, impl RxDma<T>>,
1144 config: Config,
1145 ) -> Result<Self, ConfigError> {
1146 Self::new_inner(
1147 peri,
1148 new_pin!(rx, config.rx_af()),
1149 new_pin!(tx, config.tx_af()),
1150 new_pin!(rts, config.rts_config.af_type()),
1151 new_pin!(cts, AfType::input(config.cts_pull)),
1152 None,
1153 new_dma!(tx_dma),
1154 new_dma!(rx_dma),
1155 config,
1156 )
1157 }
1158
1159 #[cfg(not(any(usart_v1, usart_v2)))]
1160 pub fn new_with_de<T: Instance>(
1162 peri: Peri<'d, T>,
1163 rx: Peri<'d, impl RxPin<T>>,
1164 tx: Peri<'d, impl TxPin<T>>,
1165 _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
1166 de: Peri<'d, impl DePin<T>>,
1167 tx_dma: Peri<'d, impl TxDma<T>>,
1168 rx_dma: Peri<'d, impl RxDma<T>>,
1169 config: Config,
1170 ) -> Result<Self, ConfigError> {
1171 Self::new_inner(
1172 peri,
1173 new_pin!(rx, config.rx_af()),
1174 new_pin!(tx, config.tx_af()),
1175 None,
1176 None,
1177 new_pin!(de, config.de_config.af_type()),
1178 new_dma!(tx_dma),
1179 new_dma!(rx_dma),
1180 config,
1181 )
1182 }
1183
1184 #[doc(alias("HDSEL"))]
1196 pub fn new_half_duplex<T: Instance>(
1197 peri: Peri<'d, T>,
1198 tx: Peri<'d, impl TxPin<T>>,
1199 _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
1200 tx_dma: Peri<'d, impl TxDma<T>>,
1201 rx_dma: Peri<'d, impl RxDma<T>>,
1202 mut config: Config,
1203 readback: HalfDuplexReadback,
1204 ) -> Result<Self, ConfigError> {
1205 #[cfg(not(any(usart_v1, usart_v2)))]
1206 {
1207 config.swap_rx_tx = false;
1208 }
1209 config.duplex = Duplex::Half(readback);
1210
1211 Self::new_inner(
1212 peri,
1213 None,
1214 new_pin!(tx, config.tx_af()),
1215 None,
1216 None,
1217 None,
1218 new_dma!(tx_dma),
1219 new_dma!(rx_dma),
1220 config,
1221 )
1222 }
1223
1224 #[cfg(not(any(usart_v1, usart_v2)))]
1234 #[doc(alias("HDSEL"))]
1235 pub fn new_half_duplex_on_rx<T: Instance>(
1236 peri: Peri<'d, T>,
1237 rx: Peri<'d, impl RxPin<T>>,
1238 _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
1239 tx_dma: Peri<'d, impl TxDma<T>>,
1240 rx_dma: Peri<'d, impl RxDma<T>>,
1241 mut config: Config,
1242 readback: HalfDuplexReadback,
1243 ) -> Result<Self, ConfigError> {
1244 config.swap_rx_tx = true;
1245 config.duplex = Duplex::Half(readback);
1246
1247 Self::new_inner(
1248 peri,
1249 None,
1250 None,
1251 new_pin!(rx, config.rx_af()),
1252 None,
1253 None,
1254 new_dma!(tx_dma),
1255 new_dma!(rx_dma),
1256 config,
1257 )
1258 }
1259
1260 pub async fn write(&mut self, buffer: &[u8]) -> Result<(), Error> {
1262 self.tx.write(buffer).await
1263 }
1264
1265 pub async fn flush(&mut self) -> Result<(), Error> {
1267 self.tx.flush().await
1268 }
1269
1270 pub async fn read(&mut self, buffer: &mut [u8]) -> Result<(), Error> {
1272 self.rx.read(buffer).await
1273 }
1274
1275 pub async fn read_until_idle(&mut self, buffer: &mut [u8]) -> Result<usize, Error> {
1277 self.rx.read_until_idle(buffer).await
1278 }
1279}
1280
1281impl<'d> Uart<'d, Blocking> {
1282 pub fn new_blocking<T: Instance>(
1284 peri: Peri<'d, T>,
1285 rx: Peri<'d, impl RxPin<T>>,
1286 tx: Peri<'d, impl TxPin<T>>,
1287 config: Config,
1288 ) -> Result<Self, ConfigError> {
1289 Self::new_inner(
1290 peri,
1291 new_pin!(rx, config.rx_af()),
1292 new_pin!(tx, config.tx_af()),
1293 None,
1294 None,
1295 None,
1296 None,
1297 None,
1298 config,
1299 )
1300 }
1301
1302 pub fn new_blocking_with_rtscts<T: Instance>(
1304 peri: Peri<'d, T>,
1305 rx: Peri<'d, impl RxPin<T>>,
1306 tx: Peri<'d, impl TxPin<T>>,
1307 rts: Peri<'d, impl RtsPin<T>>,
1308 cts: Peri<'d, impl CtsPin<T>>,
1309 config: Config,
1310 ) -> Result<Self, ConfigError> {
1311 Self::new_inner(
1312 peri,
1313 new_pin!(rx, config.rx_af()),
1314 new_pin!(tx, config.tx_af()),
1315 new_pin!(rts, config.rts_config.af_type()),
1316 new_pin!(cts, AfType::input(config.cts_pull)),
1317 None,
1318 None,
1319 None,
1320 config,
1321 )
1322 }
1323
1324 #[cfg(not(any(usart_v1, usart_v2)))]
1325 pub fn new_blocking_with_de<T: Instance>(
1327 peri: Peri<'d, T>,
1328 rx: Peri<'d, impl RxPin<T>>,
1329 tx: Peri<'d, impl TxPin<T>>,
1330 de: Peri<'d, impl DePin<T>>,
1331 config: Config,
1332 ) -> Result<Self, ConfigError> {
1333 Self::new_inner(
1334 peri,
1335 new_pin!(rx, config.rx_af()),
1336 new_pin!(tx, config.tx_af()),
1337 None,
1338 None,
1339 new_pin!(de, config.de_config.af_type()),
1340 None,
1341 None,
1342 config,
1343 )
1344 }
1345
1346 #[doc(alias("HDSEL"))]
1357 pub fn new_blocking_half_duplex<T: Instance>(
1358 peri: Peri<'d, T>,
1359 tx: Peri<'d, impl TxPin<T>>,
1360 mut config: Config,
1361 readback: HalfDuplexReadback,
1362 ) -> Result<Self, ConfigError> {
1363 #[cfg(not(any(usart_v1, usart_v2)))]
1364 {
1365 config.swap_rx_tx = false;
1366 }
1367 config.duplex = Duplex::Half(readback);
1368
1369 Self::new_inner(
1370 peri,
1371 None,
1372 new_pin!(tx, config.tx_af()),
1373 None,
1374 None,
1375 None,
1376 None,
1377 None,
1378 config,
1379 )
1380 }
1381
1382 #[cfg(not(any(usart_v1, usart_v2)))]
1392 #[doc(alias("HDSEL"))]
1393 pub fn new_blocking_half_duplex_on_rx<T: Instance>(
1394 peri: Peri<'d, T>,
1395 rx: Peri<'d, impl RxPin<T>>,
1396 mut config: Config,
1397 readback: HalfDuplexReadback,
1398 ) -> Result<Self, ConfigError> {
1399 config.swap_rx_tx = true;
1400 config.duplex = Duplex::Half(readback);
1401
1402 Self::new_inner(
1403 peri,
1404 None,
1405 None,
1406 new_pin!(rx, config.rx_af()),
1407 None,
1408 None,
1409 None,
1410 None,
1411 config,
1412 )
1413 }
1414}
1415
1416impl<'d, M: Mode> Uart<'d, M> {
1417 fn new_inner<T: Instance>(
1418 _peri: Peri<'d, T>,
1419 rx: Option<Peri<'d, AnyPin>>,
1420 tx: Option<Peri<'d, AnyPin>>,
1421 rts: Option<Peri<'d, AnyPin>>,
1422 cts: Option<Peri<'d, AnyPin>>,
1423 de: Option<Peri<'d, AnyPin>>,
1424 tx_dma: Option<ChannelAndRequest<'d>>,
1425 rx_dma: Option<ChannelAndRequest<'d>>,
1426 config: Config,
1427 ) -> Result<Self, ConfigError> {
1428 let info = T::info();
1429 let state = T::state();
1430 let kernel_clock = T::frequency();
1431
1432 let mut this = Self {
1433 tx: UartTx {
1434 _phantom: PhantomData,
1435 info,
1436 state,
1437 kernel_clock,
1438 tx,
1439 cts,
1440 de,
1441 tx_dma,
1442 duplex: config.duplex,
1443 },
1444 rx: UartRx {
1445 _phantom: PhantomData,
1446 info,
1447 state,
1448 kernel_clock,
1449 rx,
1450 rts,
1451 rx_dma,
1452 detect_previous_overrun: config.detect_previous_overrun,
1453 #[cfg(any(usart_v1, usart_v2))]
1454 buffered_sr: regs::Sr(0),
1455 },
1456 };
1457 this.enable_and_configure(&config)?;
1458 Ok(this)
1459 }
1460
1461 fn enable_and_configure(&mut self, config: &Config) -> Result<(), ConfigError> {
1462 let info = self.rx.info;
1463 let state = self.rx.state;
1464 state.tx_rx_refcount.store(2, Ordering::Relaxed);
1465
1466 info.rcc.enable_and_reset();
1467
1468 info.regs.cr3().write(|w| {
1469 w.set_rtse(self.rx.rts.is_some());
1470 w.set_ctse(self.tx.cts.is_some());
1471 #[cfg(not(any(usart_v1, usart_v2)))]
1472 w.set_dem(self.tx.de.is_some());
1473 });
1474 configure(info, self.rx.kernel_clock, config, true, true)?;
1475
1476 info.interrupt.unpend();
1477 unsafe { info.interrupt.enable() };
1478
1479 Ok(())
1480 }
1481
1482 pub fn blocking_write(&mut self, buffer: &[u8]) -> Result<(), Error> {
1484 self.tx.blocking_write(buffer)
1485 }
1486
1487 pub fn blocking_flush(&mut self) -> Result<(), Error> {
1489 self.tx.blocking_flush()
1490 }
1491
1492 pub(crate) fn nb_read(&mut self) -> Result<u8, nb::Error<Error>> {
1494 self.rx.nb_read()
1495 }
1496
1497 pub fn blocking_read(&mut self, buffer: &mut [u8]) -> Result<(), Error> {
1499 self.rx.blocking_read(buffer)
1500 }
1501
1502 pub fn split(self) -> (UartTx<'d, M>, UartRx<'d, M>) {
1506 (self.tx, self.rx)
1507 }
1508
1509 pub fn split_ref(&mut self) -> (&mut UartTx<'d, M>, &mut UartRx<'d, M>) {
1513 (&mut self.tx, &mut self.rx)
1514 }
1515
1516 pub fn send_break(&self) {
1518 self.tx.send_break();
1519 }
1520
1521 pub fn set_baudrate(&self, baudrate: u32) -> Result<(), ConfigError> {
1523 self.tx.set_baudrate(baudrate)?;
1524 self.rx.set_baudrate(baudrate)?;
1525 Ok(())
1526 }
1527}
1528
1529fn reconfigure(info: &Info, kernel_clock: Hertz, config: &Config) -> Result<(), ConfigError> {
1530 info.interrupt.disable();
1531 let r = info.regs;
1532
1533 let cr = r.cr1().read();
1534 configure(info, kernel_clock, config, cr.re(), cr.te())?;
1535
1536 info.interrupt.unpend();
1537 unsafe { info.interrupt.enable() };
1538
1539 Ok(())
1540}
1541
1542fn calculate_brr(baud: u32, pclk: u32, presc: u32, mul: u32) -> u32 {
1543 let clock = pclk / presc;
1546
1547 let brr = clock / baud * mul;
1549
1550 let rounding = ((clock % baud) * mul + (baud / 2)) / baud;
1553
1554 brr + rounding
1555}
1556
1557fn set_baudrate(info: &Info, kernel_clock: Hertz, baudrate: u32) -> Result<(), ConfigError> {
1558 info.interrupt.disable();
1559
1560 set_usart_baudrate(info, kernel_clock, baudrate)?;
1561
1562 info.interrupt.unpend();
1563 unsafe { info.interrupt.enable() };
1564
1565 Ok(())
1566}
1567
1568fn find_and_set_brr(r: Regs, kind: Kind, kernel_clock: Hertz, baudrate: u32) -> Result<bool, ConfigError> {
1569 #[cfg(not(usart_v4))]
1570 static DIVS: [(u16, ()); 1] = [(1, ())];
1571
1572 #[cfg(usart_v4)]
1573 static DIVS: [(u16, vals::Presc); 12] = [
1574 (1, vals::Presc::DIV1),
1575 (2, vals::Presc::DIV2),
1576 (4, vals::Presc::DIV4),
1577 (6, vals::Presc::DIV6),
1578 (8, vals::Presc::DIV8),
1579 (10, vals::Presc::DIV10),
1580 (12, vals::Presc::DIV12),
1581 (16, vals::Presc::DIV16),
1582 (32, vals::Presc::DIV32),
1583 (64, vals::Presc::DIV64),
1584 (128, vals::Presc::DIV128),
1585 (256, vals::Presc::DIV256),
1586 ];
1587
1588 let (mul, brr_min, brr_max) = match kind {
1589 #[cfg(any(usart_v3, usart_v4))]
1590 Kind::Lpuart => {
1591 trace!("USART: Kind::Lpuart");
1592 (256, 0x300, 0x10_0000)
1593 }
1594 Kind::Uart => {
1595 trace!("USART: Kind::Uart");
1596 (1, 0x10, 0x1_0000)
1597 }
1598 };
1599
1600 let mut found_brr = None;
1601 #[cfg(not(usart_v1))]
1602 let mut over8 = false;
1603 #[cfg(usart_v1)]
1604 let over8 = false;
1605
1606 for &(presc, _presc_val) in &DIVS {
1607 let brr = calculate_brr(baudrate, kernel_clock.0, presc as u32, mul);
1608 trace!(
1609 "USART: presc={}, div=0x{:08x} (mantissa = {}, fraction = {})",
1610 presc,
1611 brr,
1612 brr >> 4,
1613 brr & 0x0F
1614 );
1615
1616 if brr < brr_min {
1617 #[cfg(not(usart_v1))]
1618 if brr * 2 >= brr_min && kind == Kind::Uart && !cfg!(usart_v1) {
1619 over8 = true;
1620 r.brr().write_value(regs::Brr(((brr << 1) & !0xF) | (brr & 0x07)));
1621 #[cfg(usart_v4)]
1622 r.presc().write(|w| w.set_prescaler(_presc_val));
1623 found_brr = Some(brr);
1624 break;
1625 }
1626 return Err(ConfigError::BaudrateTooHigh);
1627 }
1628
1629 if brr < brr_max {
1630 r.brr().write_value(regs::Brr(brr));
1631 #[cfg(usart_v4)]
1632 r.presc().write(|w| w.set_prescaler(_presc_val));
1633 found_brr = Some(brr);
1634 break;
1635 }
1636 }
1637
1638 match found_brr {
1639 Some(brr) => {
1640 #[cfg(not(usart_v1))]
1641 let oversampling = if over8 { "8 bit" } else { "16 bit" };
1642 #[cfg(usart_v1)]
1643 let oversampling = "default";
1644 trace!(
1645 "Using {} oversampling, desired baudrate: {}, actual baudrate: {}",
1646 oversampling,
1647 baudrate,
1648 kernel_clock.0 / brr * mul
1649 );
1650 Ok(over8)
1651 }
1652 None => Err(ConfigError::BaudrateTooLow),
1653 }
1654}
1655
1656fn set_usart_baudrate(info: &Info, kernel_clock: Hertz, baudrate: u32) -> Result<(), ConfigError> {
1657 let r = info.regs;
1658 r.cr1().modify(|w| {
1659 w.set_ue(false);
1661 });
1662
1663 #[cfg(not(usart_v1))]
1664 let over8 = find_and_set_brr(r, info.kind, kernel_clock, baudrate)?;
1665 #[cfg(usart_v1)]
1666 let _over8 = find_and_set_brr(r, info.kind, kernel_clock, baudrate)?;
1667
1668 r.cr1().modify(|w| {
1669 w.set_ue(true);
1671
1672 #[cfg(not(usart_v1))]
1673 w.set_over8(vals::Over8::from_bits(over8 as _));
1674 });
1675
1676 Ok(())
1677}
1678
1679fn configure(
1680 info: &Info,
1681 kernel_clock: Hertz,
1682 config: &Config,
1683 enable_rx: bool,
1684 enable_tx: bool,
1685) -> Result<(), ConfigError> {
1686 let r = info.regs;
1687 let kind = info.kind;
1688
1689 if !enable_rx && !enable_tx {
1690 return Err(ConfigError::RxOrTxNotEnabled);
1691 }
1692
1693 r.cr1().modify(|w| {
1695 w.set_ue(false);
1696 });
1697
1698 #[cfg(not(usart_v1))]
1699 let over8 = find_and_set_brr(r, kind, kernel_clock, config.baudrate)?;
1700 #[cfg(usart_v1)]
1701 let _over8 = find_and_set_brr(r, kind, kernel_clock, config.baudrate)?;
1702
1703 r.cr2().write(|w| {
1704 w.set_stop(match config.stop_bits {
1705 StopBits::STOP0P5 => vals::Stop::STOP0P5,
1706 StopBits::STOP1 => vals::Stop::STOP1,
1707 StopBits::STOP1P5 => vals::Stop::STOP1P5,
1708 StopBits::STOP2 => vals::Stop::STOP2,
1709 });
1710
1711 #[cfg(any(usart_v3, usart_v4))]
1712 {
1713 w.set_txinv(config.invert_tx);
1714 w.set_rxinv(config.invert_rx);
1715 w.set_swap(config.swap_rx_tx);
1716 }
1717 });
1718
1719 r.cr3().modify(|w| {
1720 #[cfg(not(usart_v1))]
1721 w.set_onebit(config.assume_noise_free);
1722 w.set_hdsel(config.duplex.is_half());
1723 });
1724
1725 r.cr1().write(|w| {
1726 w.set_ue(true);
1728
1729 if config.duplex.is_half() {
1730 w.set_te(false);
1733 w.set_re(true);
1734 } else {
1735 w.set_te(enable_tx);
1737 w.set_re(enable_rx);
1739 }
1740
1741 match (config.parity, config.data_bits) {
1744 (Parity::ParityNone, DataBits::DataBits8) => {
1745 trace!("USART: m0: 8 data bits, no parity");
1746 w.set_m0(vals::M0::BIT8);
1747 #[cfg(any(usart_v3, usart_v4))]
1748 w.set_m1(vals::M1::M0);
1749 w.set_pce(false);
1750 }
1751 (Parity::ParityNone, DataBits::DataBits9) => {
1752 trace!("USART: m0: 9 data bits, no parity");
1753 w.set_m0(vals::M0::BIT9);
1754 #[cfg(any(usart_v3, usart_v4))]
1755 w.set_m1(vals::M1::M0);
1756 w.set_pce(false);
1757 }
1758 #[cfg(any(usart_v3, usart_v4))]
1759 (Parity::ParityNone, DataBits::DataBits7) => {
1760 trace!("USART: m0: 7 data bits, no parity");
1761 w.set_m0(vals::M0::BIT8);
1762 w.set_m1(vals::M1::BIT7);
1763 w.set_pce(false);
1764 }
1765 (Parity::ParityEven, DataBits::DataBits8) => {
1766 trace!("USART: m0: 8 data bits, even parity");
1767 w.set_m0(vals::M0::BIT9);
1768 #[cfg(any(usart_v3, usart_v4))]
1769 w.set_m1(vals::M1::M0);
1770 w.set_pce(true);
1771 w.set_ps(vals::Ps::EVEN);
1772 }
1773 (Parity::ParityEven, DataBits::DataBits7) => {
1774 trace!("USART: m0: 7 data bits, even parity");
1775 w.set_m0(vals::M0::BIT8);
1776 #[cfg(any(usart_v3, usart_v4))]
1777 w.set_m1(vals::M1::M0);
1778 w.set_pce(true);
1779 w.set_ps(vals::Ps::EVEN);
1780 }
1781 (Parity::ParityOdd, DataBits::DataBits8) => {
1782 trace!("USART: m0: 8 data bits, odd parity");
1783 w.set_m0(vals::M0::BIT9);
1784 #[cfg(any(usart_v3, usart_v4))]
1785 w.set_m1(vals::M1::M0);
1786 w.set_pce(true);
1787 w.set_ps(vals::Ps::ODD);
1788 }
1789 (Parity::ParityOdd, DataBits::DataBits7) => {
1790 trace!("USART: m0: 7 data bits, odd parity");
1791 w.set_m0(vals::M0::BIT8);
1792 #[cfg(any(usart_v3, usart_v4))]
1793 w.set_m1(vals::M1::M0);
1794 w.set_pce(true);
1795 w.set_ps(vals::Ps::ODD);
1796 }
1797 _ => {
1798 return Err(ConfigError::DataParityNotSupported);
1799 }
1800 }
1801 #[cfg(not(usart_v1))]
1802 w.set_over8(vals::Over8::from_bits(over8 as _));
1803 #[cfg(usart_v4)]
1804 {
1805 trace!("USART: set_fifoen: true (usart_v4)");
1806 w.set_fifoen(true);
1807 }
1808
1809 Ok(())
1810 })?;
1811
1812 Ok(())
1813}
1814
1815impl<'d, M: Mode> embedded_hal_02::serial::Read<u8> for UartRx<'d, M> {
1816 type Error = Error;
1817 fn read(&mut self) -> Result<u8, nb::Error<Self::Error>> {
1818 self.nb_read()
1819 }
1820}
1821
1822impl<'d, M: Mode> embedded_hal_02::blocking::serial::Write<u8> for UartTx<'d, M> {
1823 type Error = Error;
1824 fn bwrite_all(&mut self, buffer: &[u8]) -> Result<(), Self::Error> {
1825 self.blocking_write(buffer)
1826 }
1827 fn bflush(&mut self) -> Result<(), Self::Error> {
1828 self.blocking_flush()
1829 }
1830}
1831
1832impl<'d, M: Mode> embedded_hal_02::serial::Read<u8> for Uart<'d, M> {
1833 type Error = Error;
1834 fn read(&mut self) -> Result<u8, nb::Error<Self::Error>> {
1835 self.nb_read()
1836 }
1837}
1838
1839impl<'d, M: Mode> embedded_hal_02::blocking::serial::Write<u8> for Uart<'d, M> {
1840 type Error = Error;
1841 fn bwrite_all(&mut self, buffer: &[u8]) -> Result<(), Self::Error> {
1842 self.blocking_write(buffer)
1843 }
1844 fn bflush(&mut self) -> Result<(), Self::Error> {
1845 self.blocking_flush()
1846 }
1847}
1848
1849impl embedded_hal_nb::serial::Error for Error {
1850 fn kind(&self) -> embedded_hal_nb::serial::ErrorKind {
1851 match *self {
1852 Self::Framing => embedded_hal_nb::serial::ErrorKind::FrameFormat,
1853 Self::Noise => embedded_hal_nb::serial::ErrorKind::Noise,
1854 Self::Overrun => embedded_hal_nb::serial::ErrorKind::Overrun,
1855 Self::Parity => embedded_hal_nb::serial::ErrorKind::Parity,
1856 Self::BufferTooLong => embedded_hal_nb::serial::ErrorKind::Other,
1857 }
1858 }
1859}
1860
1861impl<'d, M: Mode> embedded_hal_nb::serial::ErrorType for Uart<'d, M> {
1862 type Error = Error;
1863}
1864
1865impl<'d, M: Mode> embedded_hal_nb::serial::ErrorType for UartTx<'d, M> {
1866 type Error = Error;
1867}
1868
1869impl<'d, M: Mode> embedded_hal_nb::serial::ErrorType for UartRx<'d, M> {
1870 type Error = Error;
1871}
1872
1873impl<'d, M: Mode> embedded_hal_nb::serial::Read for UartRx<'d, M> {
1874 fn read(&mut self) -> nb::Result<u8, Self::Error> {
1875 self.nb_read()
1876 }
1877}
1878
1879impl<'d, M: Mode> embedded_hal_nb::serial::Write for UartTx<'d, M> {
1880 fn write(&mut self, char: u8) -> nb::Result<(), Self::Error> {
1881 self.nb_write(char)
1882 }
1883
1884 fn flush(&mut self) -> nb::Result<(), Self::Error> {
1885 self.blocking_flush().map_err(nb::Error::Other)
1886 }
1887}
1888
1889impl<'d, M: Mode> embedded_hal_nb::serial::Read for Uart<'d, M> {
1890 fn read(&mut self) -> Result<u8, nb::Error<Self::Error>> {
1891 self.nb_read()
1892 }
1893}
1894
1895impl<'d, M: Mode> embedded_hal_nb::serial::Write for Uart<'d, M> {
1896 fn write(&mut self, char: u8) -> nb::Result<(), Self::Error> {
1897 self.blocking_write(&[char]).map_err(nb::Error::Other)
1898 }
1899
1900 fn flush(&mut self) -> nb::Result<(), Self::Error> {
1901 self.blocking_flush().map_err(nb::Error::Other)
1902 }
1903}
1904
1905impl embedded_io::Error for Error {
1906 fn kind(&self) -> embedded_io::ErrorKind {
1907 embedded_io::ErrorKind::Other
1908 }
1909}
1910
1911impl<M: Mode> embedded_io::ErrorType for Uart<'_, M> {
1912 type Error = Error;
1913}
1914
1915impl<M: Mode> embedded_io::ErrorType for UartTx<'_, M> {
1916 type Error = Error;
1917}
1918
1919impl<M: Mode> embedded_io::Write for Uart<'_, M> {
1920 fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
1921 self.blocking_write(buf)?;
1922 Ok(buf.len())
1923 }
1924
1925 fn flush(&mut self) -> Result<(), Self::Error> {
1926 self.blocking_flush()
1927 }
1928}
1929
1930impl<M: Mode> embedded_io::Write for UartTx<'_, M> {
1931 fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
1932 self.blocking_write(buf)?;
1933 Ok(buf.len())
1934 }
1935
1936 fn flush(&mut self) -> Result<(), Self::Error> {
1937 self.blocking_flush()
1938 }
1939}
1940
1941impl embedded_io_async::Write for Uart<'_, Async> {
1942 async fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
1943 self.write(buf).await?;
1944 Ok(buf.len())
1945 }
1946
1947 async fn flush(&mut self) -> Result<(), Self::Error> {
1948 self.flush().await
1949 }
1950}
1951
1952impl embedded_io_async::Write for UartTx<'_, Async> {
1953 async fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
1954 self.write(buf).await?;
1955 Ok(buf.len())
1956 }
1957
1958 async fn flush(&mut self) -> Result<(), Self::Error> {
1959 self.flush().await
1960 }
1961}
1962
1963pub use buffered::*;
1964
1965pub use crate::usart::buffered::InterruptHandler as BufferedInterruptHandler;
1966mod buffered;
1967
1968#[cfg(not(gpdma))]
1969mod ringbuffered;
1970#[cfg(not(gpdma))]
1971pub use ringbuffered::RingBufferedUartRx;
1972
1973#[cfg(any(usart_v1, usart_v2))]
1974fn tdr(r: crate::pac::usart::Usart) -> *mut u8 {
1975 r.dr().as_ptr() as _
1976}
1977
1978#[cfg(any(usart_v1, usart_v2))]
1979fn rdr(r: crate::pac::usart::Usart) -> *mut u8 {
1980 r.dr().as_ptr() as _
1981}
1982
1983#[cfg(any(usart_v1, usart_v2))]
1984fn sr(r: crate::pac::usart::Usart) -> crate::pac::common::Reg<regs::Sr, crate::pac::common::RW> {
1985 r.sr()
1986}
1987
1988#[cfg(any(usart_v1, usart_v2))]
1989#[allow(unused)]
1990fn clear_interrupt_flags(_r: Regs, _sr: regs::Sr) {
1991 }
1993
1994#[cfg(any(usart_v3, usart_v4))]
1995fn tdr(r: Regs) -> *mut u8 {
1996 r.tdr().as_ptr() as _
1997}
1998
1999#[cfg(any(usart_v3, usart_v4))]
2000fn rdr(r: Regs) -> *mut u8 {
2001 r.rdr().as_ptr() as _
2002}
2003
2004#[cfg(any(usart_v3, usart_v4))]
2005fn sr(r: Regs) -> crate::pac::common::Reg<regs::Isr, crate::pac::common::R> {
2006 r.isr()
2007}
2008
2009#[cfg(any(usart_v3, usart_v4))]
2010#[allow(unused)]
2011fn clear_interrupt_flags(r: Regs, sr: regs::Isr) {
2012 r.icr().write(|w| *w = regs::Icr(sr.0));
2013}
2014
2015#[derive(Clone, Copy, PartialEq, Eq)]
2016enum Kind {
2017 Uart,
2018 #[cfg(any(usart_v3, usart_v4))]
2019 #[allow(unused)]
2020 Lpuart,
2021}
2022
2023struct State {
2024 rx_waker: AtomicWaker,
2025 tx_waker: AtomicWaker,
2026 tx_rx_refcount: AtomicU8,
2027}
2028
2029impl State {
2030 const fn new() -> Self {
2031 Self {
2032 rx_waker: AtomicWaker::new(),
2033 tx_waker: AtomicWaker::new(),
2034 tx_rx_refcount: AtomicU8::new(0),
2035 }
2036 }
2037}
2038
2039struct Info {
2040 regs: Regs,
2041 rcc: RccInfo,
2042 interrupt: Interrupt,
2043 kind: Kind,
2044}
2045
2046#[allow(private_interfaces)]
2047pub(crate) trait SealedInstance: crate::rcc::RccPeripheral {
2048 fn info() -> &'static Info;
2049 fn state() -> &'static State;
2050 fn buffered_state() -> &'static buffered::State;
2051}
2052
2053#[allow(private_bounds)]
2055pub trait Instance: SealedInstance + PeripheralType + 'static + Send {
2056 type Interrupt: interrupt::typelevel::Interrupt;
2058}
2059
2060pin_trait!(RxPin, Instance);
2061pin_trait!(TxPin, Instance);
2062pin_trait!(CtsPin, Instance);
2063pin_trait!(RtsPin, Instance);
2064pin_trait!(CkPin, Instance);
2065pin_trait!(DePin, Instance);
2066
2067dma_trait!(TxDma, Instance);
2068dma_trait!(RxDma, Instance);
2069
2070macro_rules! impl_usart {
2071 ($inst:ident, $irq:ident, $kind:expr) => {
2072 #[allow(private_interfaces)]
2073 impl SealedInstance for crate::peripherals::$inst {
2074 fn info() -> &'static Info {
2075 static INFO: Info = Info {
2076 regs: unsafe { Regs::from_ptr(crate::pac::$inst.as_ptr()) },
2077 rcc: crate::peripherals::$inst::RCC_INFO,
2078 interrupt: crate::interrupt::typelevel::$irq::IRQ,
2079 kind: $kind,
2080 };
2081 &INFO
2082 }
2083
2084 fn state() -> &'static State {
2085 static STATE: State = State::new();
2086 &STATE
2087 }
2088
2089 fn buffered_state() -> &'static buffered::State {
2090 static BUFFERED_STATE: buffered::State = buffered::State::new();
2091 &BUFFERED_STATE
2092 }
2093 }
2094
2095 impl Instance for crate::peripherals::$inst {
2096 type Interrupt = crate::interrupt::typelevel::$irq;
2097 }
2098 };
2099}
2100
2101foreach_interrupt!(
2102 ($inst:ident, usart, LPUART, $signal_name:ident, $irq:ident) => {
2103 impl_usart!($inst, $irq, Kind::Lpuart);
2104 };
2105 ($inst:ident, usart, $block:ident, $signal_name:ident, $irq:ident) => {
2106 impl_usart!($inst, $irq, Kind::Uart);
2107 };
2108);