Create module uart

This commit is contained in:
gil 2024-05-13 22:12:29 -05:00
parent 556a9841e5
commit fc7eb5dfce
2 changed files with 38 additions and 14 deletions

View file

@ -4,6 +4,8 @@
use core::panic::PanicInfo;
mod uart;
#[naked]
#[no_mangle]
#[link_section = ".text.init"]
@ -28,20 +30,10 @@ unsafe extern "C" fn _start() -> ! {
}
extern "C" fn entry() -> ! {
use core::ptr::write_volatile;
let addr = 0x1000_0000 as *mut u8;
{
// Set data size to 8 bits.
unsafe { write_volatile(addr.offset(3), 0b11) };
// Enable FIFO.
unsafe { write_volatile(addr.offset(2), 0b1) };
// Enable receiver buffer interrupts.
unsafe { write_volatile(addr.offset(1), 0b1) };
}
// UART is now set up! Let's print a message.
for byte in "Hello, world!\n".bytes() {
unsafe { write_volatile(addr, byte) };
// UNSAFE: correct address for QEMU virt device
let mut console = unsafe { uart::Device::new(0x1000_0000) };
for byte in "Hello, world!".bytes() {
console.put(byte);
}
loop {}

32
src/uart.rs Normal file
View file

@ -0,0 +1,32 @@
//! This module provides access to the UART console.
/// Represents an initialised UART device.
pub struct Device {
base: usize,
}
impl Device {
/// Create a new UART device.
/// # Safety
/// `base` must be the base address of a UART device.
pub unsafe fn new(base: usize) -> Self {
use core::ptr::write_volatile;
let addr = base as *mut u8;
// Set data size to 8 bits.
unsafe { write_volatile(addr.offset(3), 0b11) };
// Enable FIFO.
unsafe { write_volatile(addr.offset(2), 0b1) };
// Enable receiver buffer interrupts.
unsafe { write_volatile(addr.offset(1), 0b1) };
// Return a new, initialised UART device.
Device { base }
}
pub fn put(&mut self, character: u8) {
let ptr = self.base as *mut u8;
// UNSAFE: fine as long as self.base is valid
unsafe {
core::ptr::write_volatile(ptr, character);
}
}
}