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, 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::scheduler::round_robin::RoundRobinSched;
23use kernel::{create_capability, debug, static_init};
24use stm32f446re::chip_specs::Stm32f446Specs;
25use stm32f446re::clocks::hsi::HSI_FREQUENCY_MHZ;
26use stm32f446re::gpio::{AlternateFunction, Mode, PinId, PortId};
27use stm32f446re::interrupt_service::Stm32f446reDefaultPeripherals;
28
29/// Support routines for debugging I/O.
30pub mod io;
31
32// Unit Tests for drivers.
33#[allow(dead_code)]
34mod virtual_uart_rx_test;
35
36// Number of concurrent processes this platform supports.
37const NUM_PROCS: usize = 4;
38
39// Actual memory for holding the active process structures.
40static mut PROCESSES: [Option<&'static dyn kernel::process::Process>; NUM_PROCS] =
41    [None, None, None, 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"]
57pub static 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    let board_kernel = static_init!(kernel::Kernel, kernel::Kernel::new(&*addr_of!(PROCESSES)));
307
308    let chip = static_init!(
309        stm32f446re::chip::Stm32f4xx<Stm32f446reDefaultPeripherals>,
310        stm32f446re::chip::Stm32f4xx::new(peripherals)
311    );
312    CHIP = Some(chip);
313
314    // UART
315
316    // Create a shared UART channel for kernel debug.
317    base_peripherals.usart2.enable_clock();
318    let uart_mux = components::console::UartMuxComponent::new(&base_peripherals.usart2, 115200)
319        .finalize(components::uart_mux_component_static!());
320
321    // `finalize()` configures the underlying USART, so we need to
322    // tell `send_byte()` not to configure the USART again.
323    (*addr_of_mut!(io::WRITER)).set_initialized();
324
325    // Create capabilities that the board needs to call certain protected kernel
326    // functions.
327    let memory_allocation_capability = create_capability!(capabilities::MemoryAllocationCapability);
328    let process_management_capability =
329        create_capability!(capabilities::ProcessManagementCapability);
330
331    // Setup the console.
332    let console = components::console::ConsoleComponent::new(
333        board_kernel,
334        capsules_core::console::DRIVER_NUM,
335        uart_mux,
336    )
337    .finalize(components::console_component_static!());
338    // Create the debugger object that handles calls to `debug!()`.
339    components::debug_writer::DebugWriterComponent::new(
340        uart_mux,
341        create_capability!(capabilities::SetDebugWriterCapability),
342    )
343    .finalize(components::debug_writer_component_static!());
344
345    // LEDs
346    let gpio_ports = &base_peripherals.gpio_ports;
347
348    // Clock to Port A is enabled in `set_pin_primary_functions()`
349    let led = components::led::LedsComponent::new().finalize(components::led_component_static!(
350        LedHigh<'static, stm32f446re::gpio::Pin>,
351        LedHigh::new(gpio_ports.get_pin(stm32f446re::gpio::PinId::PA05).unwrap()),
352    ));
353
354    // BUTTONs
355    let button = components::button::ButtonComponent::new(
356        board_kernel,
357        capsules_core::button::DRIVER_NUM,
358        components::button_component_helper!(
359            stm32f446re::gpio::Pin,
360            (
361                gpio_ports.get_pin(stm32f446re::gpio::PinId::PC13).unwrap(),
362                kernel::hil::gpio::ActivationMode::ActiveLow,
363                kernel::hil::gpio::FloatingState::PullNone
364            )
365        ),
366    )
367    .finalize(components::button_component_static!(stm32f446re::gpio::Pin));
368
369    // ALARM
370    let tim2 = &base_peripherals.tim2;
371    let mux_alarm = components::alarm::AlarmMuxComponent::new(tim2).finalize(
372        components::alarm_mux_component_static!(stm32f446re::tim2::Tim2),
373    );
374
375    let alarm = components::alarm::AlarmDriverComponent::new(
376        board_kernel,
377        capsules_core::alarm::DRIVER_NUM,
378        mux_alarm,
379    )
380    .finalize(components::alarm_component_static!(stm32f446re::tim2::Tim2));
381
382    // ADC
383    let adc_mux = components::adc::AdcMuxComponent::new(&base_peripherals.adc1)
384        .finalize(components::adc_mux_component_static!(stm32f446re::adc::Adc));
385
386    let temp_sensor = components::temperature_stm::TemperatureSTMComponent::new(
387        adc_mux,
388        stm32f446re::adc::Channel::Channel18,
389        2.5,
390        0.76,
391    )
392    .finalize(components::temperature_stm_adc_component_static!(
393        stm32f446re::adc::Adc
394    ));
395
396    let temp = components::temperature::TemperatureComponent::new(
397        board_kernel,
398        capsules_extra::temperature::DRIVER_NUM,
399        temp_sensor,
400    )
401    .finalize(components::temperature_component_static!(
402        TemperatureSTMSensor
403    ));
404
405    let adc_channel_0 =
406        components::adc::AdcComponent::new(adc_mux, stm32f446re::adc::Channel::Channel0)
407            .finalize(components::adc_component_static!(stm32f446re::adc::Adc));
408
409    let adc_channel_1 =
410        components::adc::AdcComponent::new(adc_mux, stm32f446re::adc::Channel::Channel1)
411            .finalize(components::adc_component_static!(stm32f446re::adc::Adc));
412
413    let adc_channel_2 =
414        components::adc::AdcComponent::new(adc_mux, stm32f446re::adc::Channel::Channel4)
415            .finalize(components::adc_component_static!(stm32f446re::adc::Adc));
416
417    let adc_channel_3 =
418        components::adc::AdcComponent::new(adc_mux, stm32f446re::adc::Channel::Channel8)
419            .finalize(components::adc_component_static!(stm32f446re::adc::Adc));
420
421    let adc_channel_4 =
422        components::adc::AdcComponent::new(adc_mux, stm32f446re::adc::Channel::Channel11)
423            .finalize(components::adc_component_static!(stm32f446re::adc::Adc));
424
425    let adc_channel_5 =
426        components::adc::AdcComponent::new(adc_mux, stm32f446re::adc::Channel::Channel10)
427            .finalize(components::adc_component_static!(stm32f446re::adc::Adc));
428
429    let adc_syscall =
430        components::adc::AdcVirtualComponent::new(board_kernel, capsules_core::adc::DRIVER_NUM)
431            .finalize(components::adc_syscall_component_helper!(
432                adc_channel_0,
433                adc_channel_1,
434                adc_channel_2,
435                adc_channel_3,
436                adc_channel_4,
437                adc_channel_5
438            ));
439
440    let process_printer = components::process_printer::ProcessPrinterTextComponent::new()
441        .finalize(components::process_printer_text_component_static!());
442    PROCESS_PRINTER = Some(process_printer);
443
444    // GPIO
445    let gpio = GpioComponent::new(
446        board_kernel,
447        capsules_core::gpio::DRIVER_NUM,
448        components::gpio_component_helper!(
449            stm32f446re::gpio::Pin,
450            // Arduino like RX/TX
451            // 0 => gpio_ports.get_pin(PinId::PA03).unwrap(), //D0
452            // 1 => gpio_ports.get_pin(PinId::PA02).unwrap(), //D1
453            2 => gpio_ports.get_pin(PinId::PA10).unwrap(), //D2
454            3 => gpio_ports.get_pin(PinId::PB03).unwrap(), //D3
455            4 => gpio_ports.get_pin(PinId::PB05).unwrap(), //D4
456            5 => gpio_ports.get_pin(PinId::PB04).unwrap(), //D5
457            6 => gpio_ports.get_pin(PinId::PB10).unwrap(), //D6
458            7 => gpio_ports.get_pin(PinId::PA08).unwrap(), //D7
459            8 => gpio_ports.get_pin(PinId::PA09).unwrap(), //D8
460            9 => gpio_ports.get_pin(PinId::PC07).unwrap(), //D9
461            10 => gpio_ports.get_pin(PinId::PB06).unwrap(), //D10
462            11 => gpio_ports.get_pin(PinId::PA07).unwrap(),  //D11
463            12 => gpio_ports.get_pin(PinId::PA06).unwrap(),  //D12
464            13 => gpio_ports.get_pin(PinId::PA05).unwrap(),  //D13
465            14 => gpio_ports.get_pin(PinId::PB09).unwrap(), //D14
466            15 => gpio_ports.get_pin(PinId::PB08).unwrap(), //D15
467
468            // ADC Pins
469            // Enable the to use the ADC pins as GPIO
470            // 16 => gpio_ports.get_pin(PinId::PA00).unwrap(), //A0
471            // 17 => gpio_ports.get_pin(PinId::PA01).unwrap(), //A1
472            // 18 => gpio_ports.get_pin(PinId::PA04).unwrap(), //A2
473            // 19 => gpio_ports.get_pin(PinId::PB00).unwrap(), //A3
474            // 20 => gpio_ports.get_pin(PinId::PC01).unwrap(), //A4
475            // 21 => gpio_ports.get_pin(PinId::PC00).unwrap(), //A5
476        ),
477    )
478    .finalize(components::gpio_component_static!(stm32f446re::gpio::Pin));
479
480    // PROCESS CONSOLE
481    let process_console = components::process_console::ProcessConsoleComponent::new(
482        board_kernel,
483        uart_mux,
484        mux_alarm,
485        process_printer,
486        Some(cortexm4::support::reset),
487    )
488    .finalize(components::process_console_component_static!(
489        stm32f446re::tim2::Tim2
490    ));
491    let _ = process_console.start();
492
493    let scheduler = components::sched::round_robin::RoundRobinComponent::new(&*addr_of!(PROCESSES))
494        .finalize(components::round_robin_component_static!(NUM_PROCS));
495
496    let nucleo_f446re = NucleoF446RE {
497        console,
498        ipc: kernel::ipc::IPC::new(
499            board_kernel,
500            kernel::ipc::DRIVER_NUM,
501            &memory_allocation_capability,
502        ),
503        led,
504        button,
505        adc: adc_syscall,
506        alarm,
507
508        temperature: temp,
509        gpio,
510
511        scheduler,
512        systick: cortexm4::systick::SysTick::new_with_calibration(
513            (HSI_FREQUENCY_MHZ * 1_000_000) as u32,
514        ),
515    };
516
517    // // Optional kernel tests
518    // //
519    // // See comment in `boards/imix/src/main.rs`
520    // virtual_uart_rx_test::run_virtual_uart_receive(mux_uart);
521
522    debug!("Initialization complete. Entering main loop");
523
524    // These symbols are defined in the linker script.
525    extern "C" {
526        /// Beginning of the ROM region containing app images.
527        static _sapps: u8;
528        /// End of the ROM region containing app images.
529        static _eapps: u8;
530        /// Beginning of the RAM region for app memory.
531        static mut _sappmem: u8;
532        /// End of the RAM region for app memory.
533        static _eappmem: u8;
534    }
535
536    kernel::process::load_processes(
537        board_kernel,
538        chip,
539        core::slice::from_raw_parts(
540            core::ptr::addr_of!(_sapps),
541            core::ptr::addr_of!(_eapps) as usize - core::ptr::addr_of!(_sapps) as usize,
542        ),
543        core::slice::from_raw_parts_mut(
544            core::ptr::addr_of_mut!(_sappmem),
545            core::ptr::addr_of!(_eappmem) as usize - core::ptr::addr_of!(_sappmem) as usize,
546        ),
547        &mut *addr_of_mut!(PROCESSES),
548        &FAULT_RESPONSE,
549        &process_management_capability,
550    )
551    .unwrap_or_else(|err| {
552        debug!("Error loading processes!");
553        debug!("{:?}", err);
554    });
555
556    //Uncomment to run multi alarm test
557    /*components::test::multi_alarm_test::MultiAlarmTestComponent::new(mux_alarm)
558    .finalize(components::multi_alarm_test_component_buf!(stm32f446re::tim2::Tim2))
559    .run();*/
560
561    (board_kernel, nucleo_f446re, chip)
562}
563
564/// Main function called after RAM initialized.
565#[no_mangle]
566pub unsafe fn main() {
567    let main_loop_capability = create_capability!(capabilities::MainLoopCapability);
568
569    let (board_kernel, platform, chip) = start();
570    board_kernel.kernel_loop(&platform, chip, Some(&platform.ipc), &main_loop_capability);
571}