nucleo_f446re/
main.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
5//! Board file for Nucleo-F446RE development board
6//!
7//! - <https://www.st.com/en/evaluation-tools/nucleo-f446re.html>
8
9#![no_std]
10// Disable this attribute when documenting, as a workaround for
11// https://github.com/rust-lang/rust/issues/62184.
12#![cfg_attr(not(doc), no_main)]
13#![deny(missing_docs)]
14
15use core::ptr::{addr_of, addr_of_mut};
16
17use capsules_core::virtualizers::virtual_alarm::VirtualMuxAlarm;
18use components::gpio::GpioComponent;
19use kernel::capabilities;
20use kernel::component::Component;
21use kernel::hil::gpio::Configure;
22use kernel::hil::led::LedHigh;
23use kernel::platform::{KernelResources, SyscallDriverLookup};
24use kernel::scheduler::round_robin::RoundRobinSched;
25use kernel::{create_capability, debug, static_init};
26use stm32f446re::chip_specs::Stm32f446Specs;
27use stm32f446re::clocks::hsi::HSI_FREQUENCY_MHZ;
28use stm32f446re::gpio::{AlternateFunction, Mode, PinId, PortId};
29use stm32f446re::interrupt_service::Stm32f446reDefaultPeripherals;
30
31/// Support routines for debugging I/O.
32pub mod io;
33
34// Unit Tests for drivers.
35#[allow(dead_code)]
36mod virtual_uart_rx_test;
37
38// Number of concurrent processes this platform supports.
39const NUM_PROCS: usize = 4;
40
41// Actual memory for holding the active process structures.
42static mut PROCESSES: [Option<&'static dyn kernel::process::Process>; NUM_PROCS] =
43    [None, None, None, None];
44
45// Static reference to chip for panic dumps.
46static mut CHIP: Option<&'static stm32f446re::chip::Stm32f4xx<Stm32f446reDefaultPeripherals>> =
47    None;
48// Static reference to process printer for panic dumps.
49static mut PROCESS_PRINTER: Option<&'static capsules_system::process_printer::ProcessPrinterText> =
50    None;
51
52// How should the kernel respond when a process faults.
53const FAULT_RESPONSE: capsules_system::process_policies::PanicFaultPolicy =
54    capsules_system::process_policies::PanicFaultPolicy {};
55
56/// Dummy buffer that causes the linker to reserve enough space for the stack.
57#[no_mangle]
58#[link_section = ".stack_buffer"]
59pub static mut STACK_MEMORY: [u8; 0x2000] = [0; 0x2000];
60
61type TemperatureSTMSensor = components::temperature_stm::TemperatureSTMComponentType<
62    capsules_core::virtualizers::virtual_adc::AdcDevice<'static, stm32f446re::adc::Adc<'static>>,
63>;
64type TemperatureDriver = components::temperature::TemperatureComponentType<TemperatureSTMSensor>;
65
66/// A structure representing this platform that holds references to all
67/// capsules for this platform.
68struct NucleoF446RE {
69    console: &'static capsules_core::console::Console<'static>,
70    ipc: kernel::ipc::IPC<{ NUM_PROCS as u8 }>,
71    led: &'static capsules_core::led::LedDriver<
72        'static,
73        LedHigh<'static, stm32f446re::gpio::Pin<'static>>,
74        1,
75    >,
76    button: &'static capsules_core::button::Button<'static, stm32f446re::gpio::Pin<'static>>,
77    adc: &'static capsules_core::adc::AdcVirtualized<'static>,
78    alarm: &'static capsules_core::alarm::AlarmDriver<
79        'static,
80        VirtualMuxAlarm<'static, stm32f446re::tim2::Tim2<'static>>,
81    >,
82
83    temperature: &'static TemperatureDriver,
84    gpio: &'static capsules_core::gpio::GPIO<'static, stm32f446re::gpio::Pin<'static>>,
85
86    scheduler: &'static RoundRobinSched<'static>,
87    systick: cortexm4::systick::SysTick,
88}
89
90/// Mapping of integer syscalls to objects that implement syscalls.
91impl SyscallDriverLookup for NucleoF446RE {
92    fn with_driver<F, R>(&self, driver_num: usize, f: F) -> R
93    where
94        F: FnOnce(Option<&dyn kernel::syscall::SyscallDriver>) -> R,
95    {
96        match driver_num {
97            capsules_core::console::DRIVER_NUM => f(Some(self.console)),
98            capsules_core::led::DRIVER_NUM => f(Some(self.led)),
99            capsules_core::button::DRIVER_NUM => f(Some(self.button)),
100            capsules_core::adc::DRIVER_NUM => f(Some(self.adc)),
101            capsules_core::alarm::DRIVER_NUM => f(Some(self.alarm)),
102            capsules_extra::temperature::DRIVER_NUM => f(Some(self.temperature)),
103            capsules_core::gpio::DRIVER_NUM => f(Some(self.gpio)),
104            kernel::ipc::DRIVER_NUM => f(Some(&self.ipc)),
105            _ => f(None),
106        }
107    }
108}
109
110impl
111    KernelResources<
112        stm32f446re::chip::Stm32f4xx<
113            'static,
114            stm32f446re::interrupt_service::Stm32f446reDefaultPeripherals<'static>,
115        >,
116    > for NucleoF446RE
117{
118    type SyscallDriverLookup = Self;
119    type SyscallFilter = ();
120    type ProcessFault = ();
121    type Scheduler = RoundRobinSched<'static>;
122    type SchedulerTimer = cortexm4::systick::SysTick;
123    type WatchDog = ();
124    type ContextSwitchCallback = ();
125
126    fn syscall_driver_lookup(&self) -> &Self::SyscallDriverLookup {
127        self
128    }
129    fn syscall_filter(&self) -> &Self::SyscallFilter {
130        &()
131    }
132    fn process_fault(&self) -> &Self::ProcessFault {
133        &()
134    }
135    fn scheduler(&self) -> &Self::Scheduler {
136        self.scheduler
137    }
138    fn scheduler_timer(&self) -> &Self::SchedulerTimer {
139        &self.systick
140    }
141    fn watchdog(&self) -> &Self::WatchDog {
142        &()
143    }
144    fn context_switch_callback(&self) -> &Self::ContextSwitchCallback {
145        &()
146    }
147}
148
149/// Helper function called during bring-up that configures DMA.
150unsafe fn setup_dma(
151    dma: &stm32f446re::dma::Dma1,
152    dma_streams: &'static [stm32f446re::dma::Stream<stm32f446re::dma::Dma1>; 8],
153    usart2: &'static stm32f446re::usart::Usart<stm32f446re::dma::Dma1>,
154) {
155    use stm32f446re::dma::Dma1Peripheral;
156    use stm32f446re::usart;
157
158    dma.enable_clock();
159
160    let usart2_tx_stream = &dma_streams[Dma1Peripheral::USART2_TX.get_stream_idx()];
161    let usart2_rx_stream = &dma_streams[Dma1Peripheral::USART2_RX.get_stream_idx()];
162
163    usart2.set_dma(
164        usart::TxDMA(usart2_tx_stream),
165        usart::RxDMA(usart2_rx_stream),
166    );
167
168    usart2_tx_stream.set_client(usart2);
169    usart2_rx_stream.set_client(usart2);
170
171    usart2_tx_stream.setup(Dma1Peripheral::USART2_TX);
172    usart2_rx_stream.setup(Dma1Peripheral::USART2_RX);
173
174    cortexm4::nvic::Nvic::new(Dma1Peripheral::USART2_TX.get_stream_irqn()).enable();
175    cortexm4::nvic::Nvic::new(Dma1Peripheral::USART2_RX.get_stream_irqn()).enable();
176}
177
178/// Helper function called during bring-up that configures multiplexed I/O.
179unsafe fn set_pin_primary_functions(
180    syscfg: &stm32f446re::syscfg::Syscfg,
181    gpio_ports: &'static stm32f446re::gpio::GpioPorts<'static>,
182) {
183    syscfg.enable_clock();
184
185    gpio_ports.get_port_from_port_id(PortId::A).enable_clock();
186    gpio_ports.get_port_from_port_id(PortId::B).enable_clock();
187
188    // User LD2 is connected to PA05. Configure PA05 as `debug_gpio!(0, ...)`
189    gpio_ports.get_pin(PinId::PA05).map(|pin| {
190        pin.make_output();
191
192        // Configure kernel debug gpios as early as possible
193        kernel::debug::assign_gpios(Some(pin), None, None);
194    });
195
196    // pa2 and pa3 (USART2) is connected to ST-LINK virtual COM port
197    gpio_ports.get_pin(PinId::PA02).map(|pin| {
198        pin.set_mode(Mode::AlternateFunctionMode);
199        // AF7 is USART2_TX
200        pin.set_alternate_function(AlternateFunction::AF7);
201    });
202    gpio_ports.get_pin(PinId::PA03).map(|pin| {
203        pin.set_mode(Mode::AlternateFunctionMode);
204        // AF7 is USART2_RX
205        pin.set_alternate_function(AlternateFunction::AF7);
206    });
207
208    gpio_ports.get_port_from_port_id(PortId::C).enable_clock();
209
210    // button is connected on pc13
211    gpio_ports.get_pin(PinId::PC13).map(|pin| {
212        pin.enable_interrupt();
213    });
214
215    // enable interrupt for gpio 2
216    gpio_ports.get_pin(PinId::PA10).map(|pin| {
217        pin.enable_interrupt();
218    });
219
220    // Arduino A0
221    gpio_ports.get_pin(PinId::PA00).map(|pin| {
222        pin.set_mode(stm32f446re::gpio::Mode::AnalogMode);
223    });
224
225    // Arduino A1
226    gpio_ports.get_pin(PinId::PA01).map(|pin| {
227        pin.set_mode(stm32f446re::gpio::Mode::AnalogMode);
228    });
229
230    // Arduino A2
231    gpio_ports.get_pin(PinId::PA04).map(|pin| {
232        pin.set_mode(stm32f446re::gpio::Mode::AnalogMode);
233    });
234
235    // Arduino A3
236    gpio_ports.get_pin(PinId::PB00).map(|pin| {
237        pin.set_mode(stm32f446re::gpio::Mode::AnalogMode);
238    });
239
240    // Arduino A4
241    gpio_ports.get_pin(PinId::PC01).map(|pin| {
242        pin.set_mode(stm32f446re::gpio::Mode::AnalogMode);
243    });
244
245    // Arduino A5
246    gpio_ports.get_pin(PinId::PC00).map(|pin| {
247        pin.set_mode(stm32f446re::gpio::Mode::AnalogMode);
248    });
249}
250
251/// Helper function for miscellaneous peripheral functions
252unsafe fn setup_peripherals(tim2: &stm32f446re::tim2::Tim2) {
253    // USART2 IRQn is 38
254    cortexm4::nvic::Nvic::new(stm32f446re::nvic::USART2).enable();
255
256    // TIM2 IRQn is 28
257    tim2.enable_clock();
258    tim2.start();
259    cortexm4::nvic::Nvic::new(stm32f446re::nvic::TIM2).enable();
260}
261
262/// This is in a separate, inline(never) function so that its stack frame is
263/// removed when this function returns. Otherwise, the stack space used for
264/// these static_inits is wasted.
265#[inline(never)]
266unsafe fn start() -> (
267    &'static kernel::Kernel,
268    NucleoF446RE,
269    &'static stm32f446re::chip::Stm32f4xx<'static, Stm32f446reDefaultPeripherals<'static>>,
270) {
271    stm32f446re::init();
272
273    // We use the default HSI 16Mhz clock
274    let rcc = static_init!(stm32f446re::rcc::Rcc, stm32f446re::rcc::Rcc::new());
275    let clocks = static_init!(
276        stm32f446re::clocks::Clocks<Stm32f446Specs>,
277        stm32f446re::clocks::Clocks::new(rcc)
278    );
279
280    let syscfg = static_init!(
281        stm32f446re::syscfg::Syscfg,
282        stm32f446re::syscfg::Syscfg::new(clocks)
283    );
284    let exti = static_init!(
285        stm32f446re::exti::Exti,
286        stm32f446re::exti::Exti::new(syscfg)
287    );
288    let dma1 = static_init!(stm32f446re::dma::Dma1, stm32f446re::dma::Dma1::new(clocks));
289    let dma2 = static_init!(stm32f446re::dma::Dma2, stm32f446re::dma::Dma2::new(clocks));
290
291    let peripherals = static_init!(
292        Stm32f446reDefaultPeripherals,
293        Stm32f446reDefaultPeripherals::new(clocks, exti, dma1, dma2)
294    );
295    peripherals.init();
296    let base_peripherals = &peripherals.stm32f4;
297
298    setup_peripherals(&base_peripherals.tim2);
299
300    set_pin_primary_functions(syscfg, &base_peripherals.gpio_ports);
301
302    setup_dma(
303        dma1,
304        &base_peripherals.dma1_streams,
305        &base_peripherals.usart2,
306    );
307
308    let board_kernel = static_init!(kernel::Kernel, kernel::Kernel::new(&*addr_of!(PROCESSES)));
309
310    let chip = static_init!(
311        stm32f446re::chip::Stm32f4xx<Stm32f446reDefaultPeripherals>,
312        stm32f446re::chip::Stm32f4xx::new(peripherals)
313    );
314    CHIP = Some(chip);
315
316    // UART
317
318    // Create a shared UART channel for kernel debug.
319    base_peripherals.usart2.enable_clock();
320    let uart_mux = components::console::UartMuxComponent::new(&base_peripherals.usart2, 115200)
321        .finalize(components::uart_mux_component_static!());
322
323    // `finalize()` configures the underlying USART, so we need to
324    // tell `send_byte()` not to configure the USART again.
325    (*addr_of_mut!(io::WRITER)).set_initialized();
326
327    // Create capabilities that the board needs to call certain protected kernel
328    // functions.
329    let memory_allocation_capability = create_capability!(capabilities::MemoryAllocationCapability);
330    let process_management_capability =
331        create_capability!(capabilities::ProcessManagementCapability);
332
333    // Setup the console.
334    let console = components::console::ConsoleComponent::new(
335        board_kernel,
336        capsules_core::console::DRIVER_NUM,
337        uart_mux,
338    )
339    .finalize(components::console_component_static!());
340    // Create the debugger object that handles calls to `debug!()`.
341    components::debug_writer::DebugWriterComponent::new(uart_mux)
342        .finalize(components::debug_writer_component_static!());
343
344    // LEDs
345    let gpio_ports = &base_peripherals.gpio_ports;
346
347    // Clock to Port A is enabled in `set_pin_primary_functions()`
348    let led = components::led::LedsComponent::new().finalize(components::led_component_static!(
349        LedHigh<'static, stm32f446re::gpio::Pin>,
350        LedHigh::new(gpio_ports.get_pin(stm32f446re::gpio::PinId::PA05).unwrap()),
351    ));
352
353    // BUTTONs
354    let button = components::button::ButtonComponent::new(
355        board_kernel,
356        capsules_core::button::DRIVER_NUM,
357        components::button_component_helper!(
358            stm32f446re::gpio::Pin,
359            (
360                gpio_ports.get_pin(stm32f446re::gpio::PinId::PC13).unwrap(),
361                kernel::hil::gpio::ActivationMode::ActiveLow,
362                kernel::hil::gpio::FloatingState::PullNone
363            )
364        ),
365    )
366    .finalize(components::button_component_static!(stm32f446re::gpio::Pin));
367
368    // ALARM
369    let tim2 = &base_peripherals.tim2;
370    let mux_alarm = components::alarm::AlarmMuxComponent::new(tim2).finalize(
371        components::alarm_mux_component_static!(stm32f446re::tim2::Tim2),
372    );
373
374    let alarm = components::alarm::AlarmDriverComponent::new(
375        board_kernel,
376        capsules_core::alarm::DRIVER_NUM,
377        mux_alarm,
378    )
379    .finalize(components::alarm_component_static!(stm32f446re::tim2::Tim2));
380
381    // ADC
382    let adc_mux = components::adc::AdcMuxComponent::new(&base_peripherals.adc1)
383        .finalize(components::adc_mux_component_static!(stm32f446re::adc::Adc));
384
385    let temp_sensor = components::temperature_stm::TemperatureSTMComponent::new(
386        adc_mux,
387        stm32f446re::adc::Channel::Channel18,
388        2.5,
389        0.76,
390    )
391    .finalize(components::temperature_stm_adc_component_static!(
392        stm32f446re::adc::Adc
393    ));
394
395    let temp = components::temperature::TemperatureComponent::new(
396        board_kernel,
397        capsules_extra::temperature::DRIVER_NUM,
398        temp_sensor,
399    )
400    .finalize(components::temperature_component_static!(
401        TemperatureSTMSensor
402    ));
403
404    let adc_channel_0 =
405        components::adc::AdcComponent::new(adc_mux, stm32f446re::adc::Channel::Channel0)
406            .finalize(components::adc_component_static!(stm32f446re::adc::Adc));
407
408    let adc_channel_1 =
409        components::adc::AdcComponent::new(adc_mux, stm32f446re::adc::Channel::Channel1)
410            .finalize(components::adc_component_static!(stm32f446re::adc::Adc));
411
412    let adc_channel_2 =
413        components::adc::AdcComponent::new(adc_mux, stm32f446re::adc::Channel::Channel4)
414            .finalize(components::adc_component_static!(stm32f446re::adc::Adc));
415
416    let adc_channel_3 =
417        components::adc::AdcComponent::new(adc_mux, stm32f446re::adc::Channel::Channel8)
418            .finalize(components::adc_component_static!(stm32f446re::adc::Adc));
419
420    let adc_channel_4 =
421        components::adc::AdcComponent::new(adc_mux, stm32f446re::adc::Channel::Channel11)
422            .finalize(components::adc_component_static!(stm32f446re::adc::Adc));
423
424    let adc_channel_5 =
425        components::adc::AdcComponent::new(adc_mux, stm32f446re::adc::Channel::Channel10)
426            .finalize(components::adc_component_static!(stm32f446re::adc::Adc));
427
428    let adc_syscall =
429        components::adc::AdcVirtualComponent::new(board_kernel, capsules_core::adc::DRIVER_NUM)
430            .finalize(components::adc_syscall_component_helper!(
431                adc_channel_0,
432                adc_channel_1,
433                adc_channel_2,
434                adc_channel_3,
435                adc_channel_4,
436                adc_channel_5
437            ));
438
439    let process_printer = components::process_printer::ProcessPrinterTextComponent::new()
440        .finalize(components::process_printer_text_component_static!());
441    PROCESS_PRINTER = Some(process_printer);
442
443    // GPIO
444    let gpio = GpioComponent::new(
445        board_kernel,
446        capsules_core::gpio::DRIVER_NUM,
447        components::gpio_component_helper!(
448            stm32f446re::gpio::Pin,
449            // Arduino like RX/TX
450            // 0 => gpio_ports.get_pin(PinId::PA03).unwrap(), //D0
451            // 1 => gpio_ports.get_pin(PinId::PA02).unwrap(), //D1
452            2 => gpio_ports.get_pin(PinId::PA10).unwrap(), //D2
453            3 => gpio_ports.get_pin(PinId::PB03).unwrap(), //D3
454            4 => gpio_ports.get_pin(PinId::PB05).unwrap(), //D4
455            5 => gpio_ports.get_pin(PinId::PB04).unwrap(), //D5
456            6 => gpio_ports.get_pin(PinId::PB10).unwrap(), //D6
457            7 => gpio_ports.get_pin(PinId::PA08).unwrap(), //D7
458            8 => gpio_ports.get_pin(PinId::PA09).unwrap(), //D8
459            9 => gpio_ports.get_pin(PinId::PC07).unwrap(), //D9
460            10 => gpio_ports.get_pin(PinId::PB06).unwrap(), //D10
461            11 => gpio_ports.get_pin(PinId::PA07).unwrap(),  //D11
462            12 => gpio_ports.get_pin(PinId::PA06).unwrap(),  //D12
463            13 => gpio_ports.get_pin(PinId::PA05).unwrap(),  //D13
464            14 => gpio_ports.get_pin(PinId::PB09).unwrap(), //D14
465            15 => gpio_ports.get_pin(PinId::PB08).unwrap(), //D15
466
467            // ADC Pins
468            // Enable the to use the ADC pins as GPIO
469            // 16 => gpio_ports.get_pin(PinId::PA00).unwrap(), //A0
470            // 17 => gpio_ports.get_pin(PinId::PA01).unwrap(), //A1
471            // 18 => gpio_ports.get_pin(PinId::PA04).unwrap(), //A2
472            // 19 => gpio_ports.get_pin(PinId::PB00).unwrap(), //A3
473            // 20 => gpio_ports.get_pin(PinId::PC01).unwrap(), //A4
474            // 21 => gpio_ports.get_pin(PinId::PC00).unwrap(), //A5
475        ),
476    )
477    .finalize(components::gpio_component_static!(stm32f446re::gpio::Pin));
478
479    // PROCESS CONSOLE
480    let process_console = components::process_console::ProcessConsoleComponent::new(
481        board_kernel,
482        uart_mux,
483        mux_alarm,
484        process_printer,
485        Some(cortexm4::support::reset),
486    )
487    .finalize(components::process_console_component_static!(
488        stm32f446re::tim2::Tim2
489    ));
490    let _ = process_console.start();
491
492    let scheduler = components::sched::round_robin::RoundRobinComponent::new(&*addr_of!(PROCESSES))
493        .finalize(components::round_robin_component_static!(NUM_PROCS));
494
495    let nucleo_f446re = NucleoF446RE {
496        console,
497        ipc: kernel::ipc::IPC::new(
498            board_kernel,
499            kernel::ipc::DRIVER_NUM,
500            &memory_allocation_capability,
501        ),
502        led,
503        button,
504        adc: adc_syscall,
505        alarm,
506
507        temperature: temp,
508        gpio,
509
510        scheduler,
511        systick: cortexm4::systick::SysTick::new_with_calibration(
512            (HSI_FREQUENCY_MHZ * 1_000_000) as u32,
513        ),
514    };
515
516    // // Optional kernel tests
517    // //
518    // // See comment in `boards/imix/src/main.rs`
519    // virtual_uart_rx_test::run_virtual_uart_receive(mux_uart);
520
521    debug!("Initialization complete. Entering main loop");
522
523    // These symbols are defined in the linker script.
524    extern "C" {
525        /// Beginning of the ROM region containing app images.
526        static _sapps: u8;
527        /// End of the ROM region containing app images.
528        static _eapps: u8;
529        /// Beginning of the RAM region for app memory.
530        static mut _sappmem: u8;
531        /// End of the RAM region for app memory.
532        static _eappmem: u8;
533    }
534
535    kernel::process::load_processes(
536        board_kernel,
537        chip,
538        core::slice::from_raw_parts(
539            core::ptr::addr_of!(_sapps),
540            core::ptr::addr_of!(_eapps) as usize - core::ptr::addr_of!(_sapps) as usize,
541        ),
542        core::slice::from_raw_parts_mut(
543            core::ptr::addr_of_mut!(_sappmem),
544            core::ptr::addr_of!(_eappmem) as usize - core::ptr::addr_of!(_sappmem) as usize,
545        ),
546        &mut *addr_of_mut!(PROCESSES),
547        &FAULT_RESPONSE,
548        &process_management_capability,
549    )
550    .unwrap_or_else(|err| {
551        debug!("Error loading processes!");
552        debug!("{:?}", err);
553    });
554
555    //Uncomment to run multi alarm test
556    /*components::test::multi_alarm_test::MultiAlarmTestComponent::new(mux_alarm)
557    .finalize(components::multi_alarm_test_component_buf!(stm32f446re::tim2::Tim2))
558    .run();*/
559
560    (board_kernel, nucleo_f446re, chip)
561}
562
563/// Main function called after RAM initialized.
564#[no_mangle]
565pub unsafe fn main() {
566    let main_loop_capability = create_capability!(capabilities::MainLoopCapability);
567
568    let (board_kernel, platform, chip) = start();
569    board_kernel.kernel_loop(&platform, chip, Some(&platform.ipc), &main_loop_capability);
570}