1use qingke::dm::{DATA0, DATA1};
6use qingke::riscv;
7
8const DEBUG_DATA0_ADDRESS: *mut u32 = DATA0 as *mut u32;
9const DEBUG_DATA1_ADDRESS: *mut u32 = DATA1 as *mut u32;
10
11#[cfg(afio)]
15pub fn release_swd_pins() {
16 crate::pac::AFIO.pcfr1().modify(|w| w.set_sw_cfg(0b100));
17}
18
19pub struct SDIPrint;
20
21impl SDIPrint {
22 pub fn enable() {
23 unsafe {
24 core::ptr::write_volatile(DEBUG_DATA0_ADDRESS, 0);
26 riscv::asm::delay(100000);
27 }
28 }
29
30 #[inline]
31 pub fn is_busy() -> bool {
32 unsafe { core::ptr::read_volatile(DEBUG_DATA0_ADDRESS) != 0 }
33 }
34
35 pub fn write_str_lossy(s: &str) -> core::fmt::Result {
44 write(s, Some(SPINS))
45 }
46}
47
48struct LossyWriter;
52
53impl core::fmt::Write for LossyWriter {
54 fn write_str(&mut self, s: &str) -> core::fmt::Result {
55 SDIPrint::write_str_lossy(s)
56 }
57}
58
59pub fn write_fmt_lossy(args: core::fmt::Arguments) -> core::fmt::Result {
61 use core::fmt::Write as _;
62
63 let mut writer = LossyWriter;
64 core::fmt::write(&mut writer, args)?;
65 writer.write_str("\n")
66}
67
68const SPINS: u32 = 20_000;
73
74impl core::fmt::Write for SDIPrint {
75 fn write_str(&mut self, s: &str) -> core::fmt::Result {
76 write(s, None)
77 }
78}
79
80fn write(s: &str, spins: Option<u32>) -> core::fmt::Result {
81 {
82 let mut data = [0u8; 8];
83 for chunk in s.as_bytes().chunks(7) {
84 data[1..chunk.len() + 1].copy_from_slice(chunk);
85 data[0] = chunk.len() as u8;
86
87 let data1 = u32::from_le_bytes(data[4..].try_into().unwrap());
89 let data0 = u32::from_le_bytes(data[..4].try_into().unwrap());
90
91 let mut waited = 0u32;
92 while SDIPrint::is_busy() {
93 if let Some(limit) = spins {
94 waited += 1;
95 if waited > limit {
96 return Ok(());
97 }
98 }
99 }
100
101 unsafe {
102 core::ptr::write_volatile(DEBUG_DATA1_ADDRESS, data1);
103 core::ptr::write_volatile(DEBUG_DATA0_ADDRESS, data0);
104 }
105 }
106
107 Ok(())
108 }
109}
110
111#[macro_export]
115macro_rules! try_println {
116 ($($arg:tt)*) => {
117 {
118 let _ = $crate::debug::write_fmt_lossy(format_args!($($arg)*));
121 }
122 };
123}
124
125#[macro_export]
126macro_rules! println {
127 ($($arg:tt)*) => {
128 {
129 use core::fmt::Write;
130 use core::writeln;
131
132 writeln!(&mut $crate::debug::SDIPrint, $($arg)*).unwrap();
133 }
134 }
135}
136
137#[macro_export]
138macro_rules! print {
139 ($($arg:tt)*) => {
140 {
141 use core::fmt::Write;
142 use core::write;
143
144 write!(&mut $crate::debug::SDIPrint, $($arg)*).unwrap();
145 }
146 }
147}