1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
//! Print debug information to UART0
//!
//! Directly writes to the UART0 TX uart queue.
//! This is unsafe! It is asynchronous with normal UART0 usage and
//! interrupts are not disabled.

use crate::target::UART0;

pub struct DebugLog {}

pub enum Error {}

impl DebugLog {
    pub fn count(&mut self) -> u8 {
        unsafe { (*UART0::ptr()).status.read().txfifo_cnt().bits() }
    }

    pub fn is_idle(&mut self) -> bool {
        unsafe { (*UART0::ptr()).status.read().st_utx_out().is_tx_idle() }
    }

    pub fn write(&mut self, byte: u8) -> nb::Result<(), Error> {
        if self.count() < 128 {
            unsafe { (*UART0::ptr()).tx_fifo.write_with_zero(|w| w.bits(byte)) }
            Ok(())
        } else {
            Err(nb::Error::WouldBlock)
        }
    }
}

impl core::fmt::Write for DebugLog {
    fn write_str(&mut self, s: &str) -> core::fmt::Result {
        s.as_bytes()
            .iter()
            .try_for_each(|c| nb::block!(self.write(*c)))
            .map_err(|_| core::fmt::Error)
    }
}

pub static mut DEBUG_LOG: DebugLog = DebugLog {};

/// Macro for sending a formatted string to UART0 for debugging
#[macro_export]
macro_rules! dprint {
    ($s:expr) => {
        #[allow(unused_unsafe)]
        unsafe {
            use core::fmt::Write;
            $crate::dprint::DEBUG_LOG.write_str($s).unwrap();
        }
    };
    ($($arg:tt)*) => {
        #[allow(unused_unsafe)]
        unsafe {
            use core::fmt::Write;
            $crate::dprint::DEBUG_LOG.write_fmt(format_args!($($arg)*)).unwrap();
        }
    };
}

/// Macro for sending a formatted string to UART0 for debugging, with a newline.
#[macro_export]
macro_rules! dprintln {
    () => {
        #[allow(unused_unsafe)]
        unsafe {
            use core::fmt::Write;
            $crate::dprint::DEBUG_LOG.write_str("\n").unwrap();
        }
    };
    ($fmt:expr) => {
        #[allow(unused_unsafe)]
        unsafe {
            use core::fmt::Write;
            $crate::dprint::DEBUG_LOG.write_str(concat!($fmt, "\n")).unwrap();
        }
    };
    ($fmt:expr, $($arg:tt)*) => {
        #[allow(unused_unsafe)]
        unsafe {
            use core::fmt::Write;
            $crate::dprint::DEBUG_LOG.write_fmt(format_args!(concat!($fmt, "\n"), $($arg)*)).unwrap();
        }
    };
}

/// Macro for flushing the UART0 TX buffer
#[macro_export]
macro_rules! dflush {
    () => {
        #[allow(unused_unsafe)]
        unsafe {
            while !$crate::dprint::DEBUG_LOG.is_idle() {}
        }
    };
}