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