stm32f3discovery/
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;
7use core::ptr::addr_of;
8use core::ptr::addr_of_mut;
9
10use kernel::debug;
11use kernel::debug::IoWrite;
12use kernel::hil::led;
13use kernel::hil::uart;
14use kernel::hil::uart::Configure;
15
16use stm32f303xc::gpio::PinId;
17
18use crate::CHIP;
19use crate::PROCESSES;
20use crate::PROCESS_PRINTER;
21
22/// Writer is used by kernel::debug to panic message to the serial port.
23pub struct Writer {
24    initialized: bool,
25}
26
27/// Global static for debug writer
28pub static mut WRITER: Writer = Writer { initialized: false };
29
30impl Writer {
31    /// Indicate that USART has already been initialized. Trying to double
32    /// initialize USART2 causes STM32F446RE to go into in in-deterministic state.
33    pub fn set_initialized(&mut self) {
34        self.initialized = true;
35    }
36}
37
38impl Write for Writer {
39    fn write_str(&mut self, s: &str) -> ::core::fmt::Result {
40        self.write(s.as_bytes());
41        Ok(())
42    }
43}
44
45impl IoWrite for Writer {
46    fn write(&mut self, buf: &[u8]) -> usize {
47        let rcc = stm32f303xc::rcc::Rcc::new();
48        let uart = stm32f303xc::usart::Usart::new_usart1(&rcc);
49
50        if !self.initialized {
51            self.initialized = true;
52
53            let _ = uart.configure(uart::Parameters {
54                baud_rate: 115200,
55                stop_bits: uart::StopBits::One,
56                parity: uart::Parity::None,
57                hw_flow_control: false,
58                width: uart::Width::Eight,
59            });
60        }
61
62        for &c in buf {
63            uart.send_byte(c);
64        }
65        buf.len()
66    }
67}
68
69/// Panic handler.
70#[no_mangle]
71#[panic_handler]
72pub unsafe fn panic_fmt(info: &PanicInfo) -> ! {
73    // User LD3 is connected to PE09
74    // Have to reinitialize several peripherals because otherwise can't access them here.
75    let rcc = stm32f303xc::rcc::Rcc::new();
76    let syscfg = stm32f303xc::syscfg::Syscfg::new(&rcc);
77    let exti = stm32f303xc::exti::Exti::new(&syscfg);
78    let pin = stm32f303xc::gpio::Pin::new(PinId::PE09, &exti);
79    let gpio_ports = stm32f303xc::gpio::GpioPorts::new(&rcc, &exti);
80    pin.set_ports_ref(&gpio_ports);
81    let led = &mut led::LedHigh::new(&pin);
82    let writer = &mut *addr_of_mut!(WRITER);
83
84    debug::panic(
85        &mut [led],
86        writer,
87        info,
88        &cortexm4::support::nop,
89        &*addr_of!(PROCESSES),
90        &*addr_of!(CHIP),
91        &*addr_of!(PROCESS_PRINTER),
92    )
93}