Skip to main content

tinyboot_ch32_hal/usart/
usart_common.rs

1pub use ch32_metapac::usart::Usart as Regs;
2
3#[inline(always)]
4pub fn init(r: Regs, pclk: u32, baud: u32, half_duplex: bool) {
5    // 8N1: write zeroes all bits (M=0, PCE=0, STOP=0b00), then set TE+RE
6    r.ctlr1().write(|w| {
7        w.set_te(true);
8        w.set_re(true);
9    });
10
11    // RTSE=0, CTSE=0 are default; only touch CTLR3 for half-duplex
12    if half_duplex {
13        r.ctlr3().write(|w| w.set_hdsel(true));
14    }
15
16    let brr = (pclk + baud / 2) / baud;
17    r.brr().write_value(ch32_metapac::usart::regs::Brr(brr));
18
19    r.ctlr1().modify(|w| w.set_ue(true));
20}
21
22#[inline(always)]
23pub fn read_byte(r: ch32_metapac::usart::Usart) -> u8 {
24    while !r.statr().read().rxne() {}
25    r.datar().read().dr() as u8
26}
27
28#[inline(always)]
29pub fn write_byte(r: ch32_metapac::usart::Usart, byte: u8) {
30    while !r.statr().read().txe() {}
31    r.datar().write(|w| w.set_dr(byte as u16));
32}
33
34#[inline(always)]
35pub fn flush(r: ch32_metapac::usart::Usart) {
36    while !r.statr().read().tc() {}
37}