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