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