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