microbit_v2/
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 2022.
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 nrf52833::gpio::Pin;
13use nrf52833::uart::{Uarte, 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 = 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    // MicroBit v2 has an LED matrix, use the upper left LED
76    // let mut led = Led (&gpio::PORT[Pin::P0_28], );
77
78    // MicroBit v2 has a microphone LED, use it for panic
79
80    use core::ptr::{addr_of, addr_of_mut};
81    let led_kernel_pin = &nrf52833::gpio::GPIOPin::new(Pin::P0_20);
82    let led = &mut led::LedLow::new(led_kernel_pin);
83    let writer = &mut *addr_of_mut!(WRITER);
84    debug::panic(
85        &mut [led],
86        writer,
87        pi,
88        &cortexm4::support::nop,
89        &*addr_of!(PROCESSES),
90        &*addr_of!(CHIP),
91        &*addr_of!(PROCESS_PRINTER),
92    )
93}