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