#![no_std]
use tock_registers::{
interfaces::{Readable, Writeable},
register_structs,
registers::{ReadOnly, ReadWrite},
};
register_structs! {
DW8250Regs {
(0x00 => rbr: ReadWrite<u32>),
(0x04 => ier: ReadWrite<u32>),
(0x08 => fcr: ReadWrite<u32>),
(0x0c => lcr: ReadWrite<u32>),
(0x10 => mcr: ReadWrite<u32>),
(0x14 => lsr: ReadOnly<u32>),
(0x18 => msr: ReadOnly<u32>),
(0x1c => scr: ReadWrite<u32>),
(0x20 => lpdll: ReadWrite<u32>),
(0x24 => _reserved0),
(0x7c => usr: ReadOnly<u32>),
(0x80 => _reserved1),
(0xc0 => dlf: ReadWrite<u32>),
(0xc4 => @END),
}
}
pub struct DW8250 {
base_vaddr: usize,
}
impl DW8250 {
pub const fn new(base_vaddr: usize) -> Self {
Self { base_vaddr }
}
const fn regs(&self) -> &DW8250Regs {
unsafe { &*(self.base_vaddr as *const _) }
}
pub fn init(&mut self) {
const UART_SRC_CLK: u32 = 25000000;
const BST_UART_DLF_LEN: u32 = 6;
const BAUDRATE: u32 = 115200;
let get_baud_divider = |baudrate| (UART_SRC_CLK << (BST_UART_DLF_LEN - 4)) / baudrate;
let divider = get_baud_divider(BAUDRATE);
while self.regs().usr.get() & 0b1 != 0 {}
self.regs().ier.set(0);
self.regs().fcr.set(1);
self.regs().mcr.set(0);
self.regs().mcr.set(self.regs().mcr.get() | (1 << 1));
self.regs().lcr.set(self.regs().lcr.get() | (1 << 7));
self.regs().rbr.set((divider >> BST_UART_DLF_LEN) & 0xff);
self.regs()
.ier
.set((divider >> (BST_UART_DLF_LEN + 8)) & 0xff);
self.regs().dlf.set(divider & ((1 << BST_UART_DLF_LEN) - 1));
self.regs().lcr.set(self.regs().lcr.get() & !(1 << 7));
self.regs().lcr.set(self.regs().lcr.get() | 0b11);
}
pub fn putchar(&mut self, c: u8) {
while self.regs().lsr.get() & (1 << 6) == 0 {}
self.regs().rbr.set(c as u32);
}
pub fn getchar(&mut self) -> Option<u8> {
if self.regs().lsr.get() & 0b1 != 0 {
Some((self.regs().rbr.get() & 0xff) as u8)
} else {
None
}
}
pub fn set_ier(&mut self, enable: bool) {
if enable {
self.regs().ier.set(1);
} else {
self.regs().ier.set(0);
}
}
}