weact_f401ccu6/
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 WeAct STM32F401CCU6 Core Board
6//!
7//! - <https://github.com/WeActTC/MiniF4-STM32F4x1>
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::debug::PanicResources;
20use kernel::hil::led::LedLow;
21use kernel::platform::{KernelResources, SyscallDriverLookup};
22use kernel::scheduler::round_robin::RoundRobinSched;
23use kernel::utilities::single_thread_value::SingleThreadValue;
24use kernel::{create_capability, debug, static_init};
25
26use stm32f401cc::chip_specs::Stm32f401Specs;
27use stm32f401cc::clocks::hsi::HSI_FREQUENCY_MHZ;
28use stm32f401cc::interrupt_service::Stm32f401ccDefaultPeripherals;
29
30/// Support routines for debugging I/O.
31pub mod io;
32
33// Number of concurrent processes this platform supports.
34const NUM_PROCS: usize = 4;
35
36type ChipHw = stm32f401cc::chip::Stm32f4xx<'static, Stm32f401ccDefaultPeripherals<'static>>;
37type ProcessPrinterInUse = capsules_system::process_printer::ProcessPrinterText;
38
39/// Resources for when a board panics used by io.rs.
40static PANIC_RESOURCES: SingleThreadValue<PanicResources<ChipHw, ProcessPrinterInUse>> =
41    SingleThreadValue::new(PanicResources::new());
42
43// How should the kernel respond when a process faults.
44const FAULT_RESPONSE: capsules_system::process_policies::PanicFaultPolicy =
45    capsules_system::process_policies::PanicFaultPolicy {};
46
47kernel::stack_size! {0x2000}
48
49/// A structure representing this platform that holds references to all
50/// capsules for this platform.
51struct WeactF401CC {
52    console: &'static capsules_core::console::Console<'static>,
53    ipc: kernel::ipc::IPC<{ NUM_PROCS as u8 }>,
54    led: &'static capsules_core::led::LedDriver<
55        'static,
56        LedLow<'static, stm32f401cc::gpio::Pin<'static>>,
57        1,
58    >,
59    button: &'static capsules_core::button::Button<'static, stm32f401cc::gpio::Pin<'static>>,
60    adc: &'static capsules_core::adc::AdcVirtualized<'static>,
61    alarm: &'static capsules_core::alarm::AlarmDriver<
62        'static,
63        VirtualMuxAlarm<'static, stm32f401cc::tim2::Tim2<'static>>,
64    >,
65    gpio: &'static capsules_core::gpio::GPIO<'static, stm32f401cc::gpio::Pin<'static>>,
66    scheduler: &'static RoundRobinSched<'static>,
67    systick: cortexm4::systick::SysTick,
68}
69
70/// Mapping of integer syscalls to objects that implement syscalls.
71impl SyscallDriverLookup for WeactF401CC {
72    fn with_driver<F, R>(&self, driver_num: usize, f: F) -> R
73    where
74        F: FnOnce(Option<&dyn kernel::syscall::SyscallDriver>) -> R,
75    {
76        match driver_num {
77            capsules_core::console::DRIVER_NUM => f(Some(self.console)),
78            capsules_core::led::DRIVER_NUM => f(Some(self.led)),
79            capsules_core::button::DRIVER_NUM => f(Some(self.button)),
80            capsules_core::adc::DRIVER_NUM => f(Some(self.adc)),
81            capsules_core::alarm::DRIVER_NUM => f(Some(self.alarm)),
82            kernel::ipc::DRIVER_NUM => f(Some(&self.ipc)),
83            capsules_core::gpio::DRIVER_NUM => f(Some(self.gpio)),
84            _ => f(None),
85        }
86    }
87}
88
89impl KernelResources<stm32f401cc::chip::Stm32f4xx<'static, Stm32f401ccDefaultPeripherals<'static>>>
90    for WeactF401CC
91{
92    type SyscallDriverLookup = Self;
93    type SyscallFilter = ();
94    type ProcessFault = ();
95    type Scheduler = RoundRobinSched<'static>;
96    type SchedulerTimer = cortexm4::systick::SysTick;
97    type WatchDog = ();
98    type ContextSwitchCallback = ();
99
100    fn syscall_driver_lookup(&self) -> &Self::SyscallDriverLookup {
101        self
102    }
103    fn syscall_filter(&self) -> &Self::SyscallFilter {
104        &()
105    }
106    fn process_fault(&self) -> &Self::ProcessFault {
107        &()
108    }
109    fn scheduler(&self) -> &Self::Scheduler {
110        self.scheduler
111    }
112    fn scheduler_timer(&self) -> &Self::SchedulerTimer {
113        &self.systick
114    }
115    fn watchdog(&self) -> &Self::WatchDog {
116        &()
117    }
118    fn context_switch_callback(&self) -> &Self::ContextSwitchCallback {
119        &()
120    }
121}
122
123/// Helper function called during bring-up that configures DMA.
124unsafe fn setup_dma(
125    dma: &stm32f401cc::dma::Dma1,
126    dma_streams: &'static [stm32f401cc::dma::Stream<stm32f401cc::dma::Dma1>; 8],
127    usart2: &'static stm32f401cc::usart::Usart<stm32f401cc::dma::Dma1>,
128) {
129    use stm32f401cc::dma::Dma1Peripheral;
130    use stm32f401cc::usart;
131
132    dma.enable_clock();
133
134    let usart2_tx_stream = &dma_streams[Dma1Peripheral::USART2_TX.get_stream_idx()];
135    let usart2_rx_stream = &dma_streams[Dma1Peripheral::USART2_RX.get_stream_idx()];
136
137    usart2.set_dma(
138        usart::TxDMA(usart2_tx_stream),
139        usart::RxDMA(usart2_rx_stream),
140    );
141
142    usart2_tx_stream.set_client(usart2);
143    usart2_rx_stream.set_client(usart2);
144
145    usart2_tx_stream.setup(Dma1Peripheral::USART2_TX);
146    usart2_rx_stream.setup(Dma1Peripheral::USART2_RX);
147
148    cortexm4::nvic::Nvic::new(Dma1Peripheral::USART2_TX.get_stream_irqn()).enable();
149    cortexm4::nvic::Nvic::new(Dma1Peripheral::USART2_RX.get_stream_irqn()).enable();
150}
151
152/// Helper function called during bring-up that configures multiplexed I/O.
153unsafe fn set_pin_primary_functions(
154    syscfg: &stm32f401cc::syscfg::Syscfg,
155    gpio_ports: &'static stm32f401cc::gpio::GpioPorts<'static>,
156) {
157    use kernel::hil::gpio::Configure;
158    use stm32f401cc::gpio::{AlternateFunction, Mode, PinId, PortId};
159
160    syscfg.enable_clock();
161
162    gpio_ports.get_port_from_port_id(PortId::A).enable_clock();
163
164    // On-board KEY button is connected on PA0
165    gpio_ports.get_pin(PinId::PA00).map(|pin| {
166        pin.enable_interrupt();
167    });
168
169    // enable interrupt for D3
170    gpio_ports.get_pin(PinId::PC14).map(|pin| {
171        pin.enable_interrupt();
172    });
173
174    // PA2 (tx) and PA3 (rx) (USART2)
175    gpio_ports.get_pin(PinId::PA02).map(|pin| {
176        pin.set_mode(Mode::AlternateFunctionMode);
177        // AF7 is USART2_TX
178        pin.set_alternate_function(AlternateFunction::AF7);
179    });
180    gpio_ports.get_pin(PinId::PA03).map(|pin| {
181        pin.set_mode(Mode::AlternateFunctionMode);
182        // AF7 is USART2_RX
183        pin.set_alternate_function(AlternateFunction::AF7);
184    });
185
186    gpio_ports.get_port_from_port_id(PortId::C).enable_clock();
187
188    // On-board LED C13 is connected to PC13. Configure PC13 as `debug_gpio!(0, ...)`
189    gpio_ports.get_pin(PinId::PC13).map(|pin| {
190        pin.make_output();
191        // Configure kernel debug gpios as early as possible
192        let debug_gpios = static_init!([&'static dyn kernel::hil::gpio::Pin; 1], [pin]);
193        kernel::debug::initialize_debug_gpio::<
194            <ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider,
195        >();
196        kernel::debug::assign_gpios(debug_gpios);
197    });
198
199    // Enable clocks for GPIO Ports
200    // Ports A and C enabled above, Port B is the only other board-exposed port
201    gpio_ports.get_port_from_port_id(PortId::B).enable_clock();
202}
203
204/// Helper function for miscellaneous peripheral functions
205unsafe fn setup_peripherals(tim2: &stm32f401cc::tim2::Tim2) {
206    // USART2 IRQn is 37
207    cortexm4::nvic::Nvic::new(stm32f401cc::nvic::USART2).enable();
208
209    // TIM2 IRQn is 28
210    tim2.enable_clock();
211    tim2.start();
212    cortexm4::nvic::Nvic::new(stm32f401cc::nvic::TIM2).enable();
213}
214
215/// Main function
216///
217/// This is in a separate, inline(never) function so that its stack frame is
218/// removed when this function returns. Otherwise, the stack space used for
219/// these static_inits is wasted.
220#[inline(never)]
221unsafe fn start() -> (
222    &'static kernel::Kernel,
223    WeactF401CC,
224    &'static stm32f401cc::chip::Stm32f4xx<'static, Stm32f401ccDefaultPeripherals<'static>>,
225) {
226    stm32f401cc::init();
227
228    // Initialize deferred calls very early.
229    kernel::deferred_call::initialize_deferred_call_state::<
230        <ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider,
231    >();
232
233    // Bind global variables to this thread.
234    PANIC_RESOURCES.bind_to_thread::<<ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider>();
235
236    // We use the default HSI 16Mhz clock
237    let rcc = static_init!(stm32f401cc::rcc::Rcc, stm32f401cc::rcc::Rcc::new());
238    let clocks = static_init!(
239        stm32f401cc::clocks::Clocks<Stm32f401Specs>,
240        stm32f401cc::clocks::Clocks::new(rcc)
241    );
242    let syscfg = static_init!(
243        stm32f401cc::syscfg::Syscfg,
244        stm32f401cc::syscfg::Syscfg::new(clocks)
245    );
246    let exti = static_init!(
247        stm32f401cc::exti::Exti,
248        stm32f401cc::exti::Exti::new(syscfg)
249    );
250    let dma1 = static_init!(stm32f401cc::dma::Dma1, stm32f401cc::dma::Dma1::new(clocks));
251    let dma2 = static_init!(stm32f401cc::dma::Dma2, stm32f401cc::dma::Dma2::new(clocks));
252
253    let peripherals = static_init!(
254        Stm32f401ccDefaultPeripherals,
255        Stm32f401ccDefaultPeripherals::new(clocks, exti, dma1, dma2)
256    );
257
258    peripherals.init();
259    let base_peripherals = &peripherals.stm32f4;
260
261    setup_peripherals(&base_peripherals.tim2);
262
263    set_pin_primary_functions(syscfg, &base_peripherals.gpio_ports);
264
265    setup_dma(
266        dma1,
267        &base_peripherals.dma1_streams,
268        &base_peripherals.usart2,
269    );
270
271    // Create an array to hold process references.
272    let processes = components::process_array::ProcessArrayComponent::new()
273        .finalize(components::process_array_component_static!(NUM_PROCS));
274    PANIC_RESOURCES.get().map(|resources| {
275        resources.processes.put(processes.as_slice());
276    });
277
278    // Setup space to store the core kernel data structure.
279    let board_kernel = static_init!(kernel::Kernel, kernel::Kernel::new(processes.as_slice()));
280
281    let chip = static_init!(
282        stm32f401cc::chip::Stm32f4xx<Stm32f401ccDefaultPeripherals>,
283        stm32f401cc::chip::Stm32f4xx::new(peripherals)
284    );
285    PANIC_RESOURCES.get().map(|resources| {
286        resources.chip.put(chip);
287    });
288
289    // UART
290
291    // Create a shared UART channel for kernel debug.
292    base_peripherals.usart2.enable_clock();
293    let uart_mux = components::console::UartMuxComponent::new(&base_peripherals.usart2, 115200)
294        .finalize(components::uart_mux_component_static!());
295
296    (*addr_of_mut!(io::WRITER)).set_initialized();
297
298    // Create capabilities that the board needs to call certain protected kernel
299    // functions.
300    let memory_allocation_capability = create_capability!(capabilities::MemoryAllocationCapability);
301    let process_management_capability =
302        create_capability!(capabilities::ProcessManagementCapability);
303
304    // Setup the console.
305    let console = components::console::ConsoleComponent::new(
306        board_kernel,
307        capsules_core::console::DRIVER_NUM,
308        uart_mux,
309    )
310    .finalize(components::console_component_static!());
311    // Create the debugger object that handles calls to `debug!()`.
312    components::debug_writer::DebugWriterComponent::new::<
313        <ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider,
314    >(
315        uart_mux,
316        create_capability!(capabilities::SetDebugWriterCapability),
317    )
318    .finalize(components::debug_writer_component_static!());
319
320    // LEDs
321    // Clock to Port A, B, C are enabled in `set_pin_primary_functions()`
322    let gpio_ports = &base_peripherals.gpio_ports;
323
324    let led = components::led::LedsComponent::new().finalize(components::led_component_static!(
325        LedLow<'static, stm32f401cc::gpio::Pin>,
326        LedLow::new(gpio_ports.get_pin(stm32f401cc::gpio::PinId::PC13).unwrap()),
327    ));
328
329    // BUTTONs
330    let button = components::button::ButtonComponent::new(
331        board_kernel,
332        capsules_core::button::DRIVER_NUM,
333        components::button_component_helper!(
334            stm32f401cc::gpio::Pin,
335            (
336                gpio_ports.get_pin(stm32f401cc::gpio::PinId::PA00).unwrap(),
337                kernel::hil::gpio::ActivationMode::ActiveLow,
338                kernel::hil::gpio::FloatingState::PullUp
339            )
340        ),
341    )
342    .finalize(components::button_component_static!(stm32f401cc::gpio::Pin));
343
344    // ALARM
345
346    let tim2 = &base_peripherals.tim2;
347    let mux_alarm = components::alarm::AlarmMuxComponent::new(tim2).finalize(
348        components::alarm_mux_component_static!(stm32f401cc::tim2::Tim2),
349    );
350
351    let alarm = components::alarm::AlarmDriverComponent::new(
352        board_kernel,
353        capsules_core::alarm::DRIVER_NUM,
354        mux_alarm,
355    )
356    .finalize(components::alarm_component_static!(stm32f401cc::tim2::Tim2));
357
358    // GPIO
359    let gpio = GpioComponent::new(
360        board_kernel,
361        capsules_core::gpio::DRIVER_NUM,
362        components::gpio_component_helper!(
363            stm32f401cc::gpio::Pin,
364            // 2 => gpio_ports.pins[2][13].as_ref().unwrap(), // C13 (reserved for led)
365            3 => gpio_ports.pins[2][14].as_ref().unwrap(), // C14
366            4 => gpio_ports.pins[2][15].as_ref().unwrap(), // C15
367            // 10 => gpio_ports.pins[0][0].as_ref().unwrap(), // A0 (reserved for button)
368            11 => gpio_ports.pins[0][1].as_ref().unwrap(), // A1
369            12 => gpio_ports.pins[0][2].as_ref().unwrap(), // A2
370            13 => gpio_ports.pins[0][3].as_ref().unwrap(), // A3
371            14 => gpio_ports.pins[0][4].as_ref().unwrap(), // A4
372            15 => gpio_ports.pins[0][5].as_ref().unwrap(), // A5
373            16 => gpio_ports.pins[0][6].as_ref().unwrap(), // A6
374            17 => gpio_ports.pins[0][7].as_ref().unwrap(), // A7
375            18 => gpio_ports.pins[1][0].as_ref().unwrap(), // B0
376            19 => gpio_ports.pins[1][1].as_ref().unwrap(), // B1
377            20 => gpio_ports.pins[1][2].as_ref().unwrap(), // B2
378            21 => gpio_ports.pins[1][10].as_ref().unwrap(), // B10
379            25 => gpio_ports.pins[1][12].as_ref().unwrap(), // B12
380            26 => gpio_ports.pins[1][13].as_ref().unwrap(), // B13
381            27 => gpio_ports.pins[1][14].as_ref().unwrap(), // B14
382            28 => gpio_ports.pins[1][15].as_ref().unwrap(), // B15
383            29 => gpio_ports.pins[0][8].as_ref().unwrap(), // A8
384            30 => gpio_ports.pins[0][9].as_ref().unwrap(), // A9
385            31 => gpio_ports.pins[0][10].as_ref().unwrap(), // A10
386            32 => gpio_ports.pins[0][11].as_ref().unwrap(), // A11
387            33 => gpio_ports.pins[0][12].as_ref().unwrap(), // A12
388            34 => gpio_ports.pins[0][13].as_ref().unwrap(), // A13
389            37 => gpio_ports.pins[0][14].as_ref().unwrap(), // A14
390            38 => gpio_ports.pins[0][15].as_ref().unwrap(), // A15
391            39 => gpio_ports.pins[1][3].as_ref().unwrap(), // B3
392            40 => gpio_ports.pins[1][4].as_ref().unwrap(), // B4
393            41 => gpio_ports.pins[1][5].as_ref().unwrap(), // B5
394            42 => gpio_ports.pins[1][6].as_ref().unwrap(), // B6
395            43 => gpio_ports.pins[1][7].as_ref().unwrap(), // B7
396            45 => gpio_ports.pins[1][8].as_ref().unwrap(), // B8
397            46 => gpio_ports.pins[1][9].as_ref().unwrap(), // B9
398        ),
399    )
400    .finalize(components::gpio_component_static!(stm32f401cc::gpio::Pin));
401
402    // ADC
403    let adc_mux = components::adc::AdcMuxComponent::new(&base_peripherals.adc1)
404        .finalize(components::adc_mux_component_static!(stm32f401cc::adc::Adc));
405
406    let adc_channel_0 =
407        components::adc::AdcComponent::new(adc_mux, stm32f401cc::adc::Channel::Channel3)
408            .finalize(components::adc_component_static!(stm32f401cc::adc::Adc));
409
410    let adc_channel_1 =
411        components::adc::AdcComponent::new(adc_mux, stm32f401cc::adc::Channel::Channel10)
412            .finalize(components::adc_component_static!(stm32f401cc::adc::Adc));
413
414    let adc_channel_2 =
415        components::adc::AdcComponent::new(adc_mux, stm32f401cc::adc::Channel::Channel13)
416            .finalize(components::adc_component_static!(stm32f401cc::adc::Adc));
417
418    let adc_channel_3 =
419        components::adc::AdcComponent::new(adc_mux, stm32f401cc::adc::Channel::Channel9)
420            .finalize(components::adc_component_static!(stm32f401cc::adc::Adc));
421
422    let adc_channel_4 =
423        components::adc::AdcComponent::new(adc_mux, stm32f401cc::adc::Channel::Channel15)
424            .finalize(components::adc_component_static!(stm32f401cc::adc::Adc));
425
426    let adc_channel_5 =
427        components::adc::AdcComponent::new(adc_mux, stm32f401cc::adc::Channel::Channel8)
428            .finalize(components::adc_component_static!(stm32f401cc::adc::Adc));
429
430    let adc_syscall =
431        components::adc::AdcVirtualComponent::new(board_kernel, capsules_core::adc::DRIVER_NUM)
432            .finalize(components::adc_syscall_component_helper!(
433                adc_channel_0,
434                adc_channel_1,
435                adc_channel_2,
436                adc_channel_3,
437                adc_channel_4,
438                adc_channel_5
439            ));
440
441    let process_printer = components::process_printer::ProcessPrinterTextComponent::new()
442        .finalize(components::process_printer_text_component_static!());
443    PANIC_RESOURCES.get().map(|resources| {
444        resources.printer.put(process_printer);
445    });
446
447    // PROCESS CONSOLE
448    let process_console = components::process_console::ProcessConsoleComponent::new(
449        board_kernel,
450        uart_mux,
451        mux_alarm,
452        process_printer,
453        Some(cortexm4::support::reset),
454    )
455    .finalize(components::process_console_component_static!(
456        stm32f401cc::tim2::Tim2
457    ));
458    let _ = process_console.start();
459
460    let scheduler = components::sched::round_robin::RoundRobinComponent::new(processes)
461        .finalize(components::round_robin_component_static!(NUM_PROCS));
462
463    let weact_f401cc = WeactF401CC {
464        console,
465        ipc: kernel::ipc::IPC::new(
466            board_kernel,
467            kernel::ipc::DRIVER_NUM,
468            &memory_allocation_capability,
469        ),
470        adc: adc_syscall,
471        led,
472        button,
473        alarm,
474        gpio,
475        scheduler,
476        systick: cortexm4::systick::SysTick::new_with_calibration(
477            (HSI_FREQUENCY_MHZ * 1_000_000) as u32,
478        ),
479    };
480
481    debug!("Initialization complete. Entering main loop");
482
483    // These symbols are defined in the linker script.
484    extern "C" {
485        /// Beginning of the ROM region containing app images.
486        static _sapps: u8;
487        /// End of the ROM region containing app images.
488        static _eapps: u8;
489        /// Beginning of the RAM region for app memory.
490        static mut _sappmem: u8;
491        /// End of the RAM region for app memory.
492        static _eappmem: u8;
493    }
494
495    kernel::process::load_processes(
496        board_kernel,
497        chip,
498        core::slice::from_raw_parts(
499            core::ptr::addr_of!(_sapps),
500            core::ptr::addr_of!(_eapps) as usize - core::ptr::addr_of!(_sapps) as usize,
501        ),
502        core::slice::from_raw_parts_mut(
503            core::ptr::addr_of_mut!(_sappmem),
504            core::ptr::addr_of!(_eappmem) as usize - core::ptr::addr_of!(_sappmem) as usize,
505        ),
506        &FAULT_RESPONSE,
507        &process_management_capability,
508    )
509    .unwrap_or_else(|err| {
510        debug!("Error loading processes!");
511        debug!("{:?}", err);
512    });
513
514    //Uncomment to run multi alarm test
515    /*components::test::multi_alarm_test::MultiAlarmTestComponent::new(mux_alarm)
516    .finalize(components::multi_alarm_test_component_buf!(stm32f401cc::tim2::Tim2))
517    .run();*/
518
519    (board_kernel, weact_f401cc, chip)
520}
521
522/// Main function called after RAM initialized.
523#[no_mangle]
524pub unsafe fn main() {
525    let main_loop_capability = create_capability!(capabilities::MainLoopCapability);
526
527    let (board_kernel, platform, chip) = start();
528    board_kernel.kernel_loop(&platform, chip, Some(&platform.ipc), &main_loop_capability);
529}