stm32f429idiscovery/
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 stm32f429zi::chip_specs::Stm32f429Specs;
16use stm32f429zi::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 USART1 causes stm32f429zi 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 = stm32f429zi::rcc::Rcc::new();
44        let clocks: stm32f429zi::clocks::Clocks<Stm32f429Specs> =
45            stm32f429zi::clocks::Clocks::new(&rcc);
46        let uart = stm32f429zi::usart::Usart::new_usart1(&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 LD4 is connected to PG14
72    // Have to reinitialize several peripherals because otherwise can't access them here.
73    let rcc = stm32f429zi::rcc::Rcc::new();
74    let clocks: stm32f429zi::clocks::Clocks<Stm32f429Specs> =
75        stm32f429zi::clocks::Clocks::new(&rcc);
76    let syscfg = stm32f429zi::syscfg::Syscfg::new(&clocks);
77    let exti = stm32f429zi::exti::Exti::new(&syscfg);
78    let pin = stm32f429zi::gpio::Pin::new(PinId::PG14, &exti);
79    let gpio_ports = stm32f429zi::gpio::GpioPorts::new(&clocks, &exti);
80    pin.set_ports_ref(&gpio_ports);
81    let led = &mut led::LedHigh::new(&pin);
82
83    let writer = &mut *addr_of_mut!(WRITER);
84
85    debug::panic(
86        &mut [led],
87        writer,
88        info,
89        &cortexm4::support::nop,
90        crate::PANIC_RESOURCES.get(),
91    )
92}