wm1110dev/
io.rs

1// Licensed under the Apache License, Version 2.0 or the MIT License.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3// Copyright Tock Contributors 2023.
4
5use core::fmt::Write;
6use core::panic::PanicInfo;
7
8use kernel::debug;
9use kernel::debug::IoWrite;
10use kernel::hil::led;
11use kernel::hil::uart;
12use nrf52840::gpio::Pin;
13use nrf52840::uart::UARTE0_BASE;
14
15use crate::CHIP;
16use crate::PROCESSES;
17use crate::PROCESS_PRINTER;
18
19/// Writer is used by kernel::debug to panic message to the serial port.
20pub struct Writer {
21    initialized: bool,
22}
23
24impl Writer {
25    /// Indicate that USART has already been initialized.
26    pub fn set_initialized(&mut self) {
27        self.initialized = true;
28    }
29}
30
31/// Global static for debug writer
32pub static mut WRITER: Writer = Writer { initialized: false };
33
34impl Write for Writer {
35    fn write_str(&mut self, s: &str) -> ::core::fmt::Result {
36        self.write(s.as_bytes());
37        Ok(())
38    }
39}
40
41impl IoWrite for Writer {
42    fn write(&mut self, buf: &[u8]) -> usize {
43        let uart = nrf52840::uart::Uarte::new(UARTE0_BASE);
44
45        use kernel::hil::uart::Configure;
46
47        if !self.initialized {
48            self.initialized = true;
49            let _ = uart.configure(uart::Parameters {
50                baud_rate: 115200,
51                stop_bits: uart::StopBits::One,
52                parity: uart::Parity::None,
53                hw_flow_control: false,
54                width: uart::Width::Eight,
55            });
56        }
57
58        unsafe {
59            for &c in buf {
60                uart.send_byte(c);
61                while !uart.tx_ready() {}
62            }
63        }
64        buf.len()
65    }
66}
67
68/// Default panic handler for the microbit board.
69///
70/// We just use the standard default provided by the debug module in the kernel.
71#[cfg(not(test))]
72#[no_mangle]
73#[panic_handler]
74pub unsafe fn panic_fmt(pi: &PanicInfo) -> ! {
75    // Red Led
76
77    use core::ptr::{addr_of, addr_of_mut};
78    let led_red_pin = &nrf52840::gpio::GPIOPin::new(Pin::P0_14);
79    let led = &mut led::LedHigh::new(led_red_pin);
80    let writer = &mut *addr_of_mut!(WRITER);
81    debug::panic(
82        &mut [led],
83        writer,
84        pi,
85        &cortexm4::support::nop,
86        &*addr_of!(PROCESSES),
87        &*addr_of!(CHIP),
88        &*addr_of!(PROCESS_PRINTER),
89    )
90}