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