nrf52840dk_lib/
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 kernel::debug::IoWrite;
7use kernel::hil::uart;
8use kernel::hil::uart::Configure;
9
10use nrf52840::uart::{Uarte, UARTE0_BASE};
11
12enum Writer {
13    WriterUart(/* initialized */ bool),
14    WriterRtt(&'static segger::rtt::SeggerRttMemory<'static>),
15}
16
17static mut WRITER: Writer = Writer::WriterUart(false);
18
19/// Set the RTT memory buffer used to output panic messages.
20pub unsafe fn set_rtt_memory(rtt_memory: &'static segger::rtt::SeggerRttMemory<'static>) {
21    WRITER = Writer::WriterRtt(rtt_memory);
22}
23
24impl Write for Writer {
25    fn write_str(&mut self, s: &str) -> ::core::fmt::Result {
26        self.write(s.as_bytes());
27        Ok(())
28    }
29}
30
31impl IoWrite for Writer {
32    fn write(&mut self, buf: &[u8]) -> usize {
33        match self {
34            Writer::WriterUart(ref mut initialized) => {
35                // Here, we create a second instance of the Uarte struct.
36                // This is okay because we only call this during a panic, and
37                // we will never actually process the interrupts
38                let uart = Uarte::new(UARTE0_BASE);
39                if !*initialized {
40                    *initialized = true;
41                    let _ = uart.configure(uart::Parameters {
42                        baud_rate: 115200,
43                        stop_bits: uart::StopBits::One,
44                        parity: uart::Parity::None,
45                        hw_flow_control: false,
46                        width: uart::Width::Eight,
47                    });
48                }
49                for &c in buf {
50                    unsafe { uart.send_byte(c) }
51                    while !uart.tx_ready() {}
52                }
53            }
54            Writer::WriterRtt(rtt_memory) => rtt_memory.write_sync(buf),
55        }
56        buf.len()
57    }
58}
59
60#[cfg(not(test))]
61#[no_mangle]
62#[panic_handler]
63/// Panic handler
64pub unsafe fn panic_fmt(pi: &core::panic::PanicInfo) -> ! {
65    use core::ptr::{addr_of, addr_of_mut};
66    use kernel::debug;
67    use kernel::hil::led;
68    use nrf52840::gpio::Pin;
69
70    use crate::CHIP;
71    use crate::PROCESSES;
72    use crate::PROCESS_PRINTER;
73
74    // The nRF52840DK LEDs (see back of board)
75    let led_kernel_pin = &nrf52840::gpio::GPIOPin::new(Pin::P0_13);
76    let led = &mut led::LedLow::new(led_kernel_pin);
77    let writer = &mut *addr_of_mut!(WRITER);
78    debug::panic(
79        &mut [led],
80        writer,
81        pi,
82        &cortexm4::support::nop,
83        &*addr_of!(PROCESSES),
84        &*addr_of!(CHIP),
85        &*addr_of!(PROCESS_PRINTER),
86    )
87}