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
35type ChipHw = stm32f401cc::chip::Stm32f4xx<'static, Stm32f401ccDefaultPeripherals<'static>>;
36
37/// Static variables used by io.rs.
38static mut PROCESSES: Option<&'static ProcessArray<NUM_PROCS>> = None;
39static mut CHIP: Option<&'static ChipHw> = None;
40static mut PROCESS_PRINTER: Option<&'static capsules_system::process_printer::ProcessPrinterText> =
41    None;
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        kernel::debug::assign_gpios(Some(pin), None, None);
193    });
194
195    // Enable clocks for GPIO Ports
196    // Ports A and C enabled above, Port B is the only other board-exposed port
197    gpio_ports.get_port_from_port_id(PortId::B).enable_clock();
198}
199
200/// Helper function for miscellaneous peripheral functions
201unsafe fn setup_peripherals(tim2: &stm32f401cc::tim2::Tim2) {
202    // USART2 IRQn is 37
203    cortexm4::nvic::Nvic::new(stm32f401cc::nvic::USART2).enable();
204
205    // TIM2 IRQn is 28
206    tim2.enable_clock();
207    tim2.start();
208    cortexm4::nvic::Nvic::new(stm32f401cc::nvic::TIM2).enable();
209}
210
211/// Main function
212///
213/// This is in a separate, inline(never) function so that its stack frame is
214/// removed when this function returns. Otherwise, the stack space used for
215/// these static_inits is wasted.
216#[inline(never)]
217unsafe fn start() -> (
218    &'static kernel::Kernel,
219    WeactF401CC,
220    &'static stm32f401cc::chip::Stm32f4xx<'static, Stm32f401ccDefaultPeripherals<'static>>,
221) {
222    stm32f401cc::init();
223
224    // We use the default HSI 16Mhz clock
225    let rcc = static_init!(stm32f401cc::rcc::Rcc, stm32f401cc::rcc::Rcc::new());
226    let clocks = static_init!(
227        stm32f401cc::clocks::Clocks<Stm32f401Specs>,
228        stm32f401cc::clocks::Clocks::new(rcc)
229    );
230    let syscfg = static_init!(
231        stm32f401cc::syscfg::Syscfg,
232        stm32f401cc::syscfg::Syscfg::new(clocks)
233    );
234    let exti = static_init!(
235        stm32f401cc::exti::Exti,
236        stm32f401cc::exti::Exti::new(syscfg)
237    );
238    let dma1 = static_init!(stm32f401cc::dma::Dma1, stm32f401cc::dma::Dma1::new(clocks));
239    let dma2 = static_init!(stm32f401cc::dma::Dma2, stm32f401cc::dma::Dma2::new(clocks));
240
241    let peripherals = static_init!(
242        Stm32f401ccDefaultPeripherals,
243        Stm32f401ccDefaultPeripherals::new(clocks, exti, dma1, dma2)
244    );
245
246    peripherals.init();
247    let base_peripherals = &peripherals.stm32f4;
248
249    setup_peripherals(&base_peripherals.tim2);
250
251    set_pin_primary_functions(syscfg, &base_peripherals.gpio_ports);
252
253    setup_dma(
254        dma1,
255        &base_peripherals.dma1_streams,
256        &base_peripherals.usart2,
257    );
258
259    // Create an array to hold process references.
260    let processes = components::process_array::ProcessArrayComponent::new()
261        .finalize(components::process_array_component_static!(NUM_PROCS));
262    PROCESSES = Some(processes);
263
264    // Setup space to store the core kernel data structure.
265    let board_kernel = static_init!(kernel::Kernel, kernel::Kernel::new(processes.as_slice()));
266
267    let chip = static_init!(
268        stm32f401cc::chip::Stm32f4xx<Stm32f401ccDefaultPeripherals>,
269        stm32f401cc::chip::Stm32f4xx::new(peripherals)
270    );
271    CHIP = Some(chip);
272
273    // UART
274
275    // Create a shared UART channel for kernel debug.
276    base_peripherals.usart2.enable_clock();
277    let uart_mux = components::console::UartMuxComponent::new(&base_peripherals.usart2, 115200)
278        .finalize(components::uart_mux_component_static!());
279
280    (*addr_of_mut!(io::WRITER)).set_initialized();
281
282    // Create capabilities that the board needs to call certain protected kernel
283    // functions.
284    let memory_allocation_capability = create_capability!(capabilities::MemoryAllocationCapability);
285    let process_management_capability =
286        create_capability!(capabilities::ProcessManagementCapability);
287
288    // Setup the console.
289    let console = components::console::ConsoleComponent::new(
290        board_kernel,
291        capsules_core::console::DRIVER_NUM,
292        uart_mux,
293    )
294    .finalize(components::console_component_static!());
295    // Create the debugger object that handles calls to `debug!()`.
296    components::debug_writer::DebugWriterComponent::new::<
297        <ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider,
298    >(
299        uart_mux,
300        create_capability!(capabilities::SetDebugWriterCapability),
301    )
302    .finalize(components::debug_writer_component_static!());
303
304    // LEDs
305    // Clock to Port A, B, C are enabled in `set_pin_primary_functions()`
306    let gpio_ports = &base_peripherals.gpio_ports;
307
308    let led = components::led::LedsComponent::new().finalize(components::led_component_static!(
309        LedLow<'static, stm32f401cc::gpio::Pin>,
310        LedLow::new(gpio_ports.get_pin(stm32f401cc::gpio::PinId::PC13).unwrap()),
311    ));
312
313    // BUTTONs
314    let button = components::button::ButtonComponent::new(
315        board_kernel,
316        capsules_core::button::DRIVER_NUM,
317        components::button_component_helper!(
318            stm32f401cc::gpio::Pin,
319            (
320                gpio_ports.get_pin(stm32f401cc::gpio::PinId::PA00).unwrap(),
321                kernel::hil::gpio::ActivationMode::ActiveLow,
322                kernel::hil::gpio::FloatingState::PullUp
323            )
324        ),
325    )
326    .finalize(components::button_component_static!(stm32f401cc::gpio::Pin));
327
328    // ALARM
329
330    let tim2 = &base_peripherals.tim2;
331    let mux_alarm = components::alarm::AlarmMuxComponent::new(tim2).finalize(
332        components::alarm_mux_component_static!(stm32f401cc::tim2::Tim2),
333    );
334
335    let alarm = components::alarm::AlarmDriverComponent::new(
336        board_kernel,
337        capsules_core::alarm::DRIVER_NUM,
338        mux_alarm,
339    )
340    .finalize(components::alarm_component_static!(stm32f401cc::tim2::Tim2));
341
342    // GPIO
343    let gpio = GpioComponent::new(
344        board_kernel,
345        capsules_core::gpio::DRIVER_NUM,
346        components::gpio_component_helper!(
347            stm32f401cc::gpio::Pin,
348            // 2 => gpio_ports.pins[2][13].as_ref().unwrap(), // C13 (reserved for led)
349            3 => gpio_ports.pins[2][14].as_ref().unwrap(), // C14
350            4 => gpio_ports.pins[2][15].as_ref().unwrap(), // C15
351            // 10 => gpio_ports.pins[0][0].as_ref().unwrap(), // A0 (reserved for button)
352            11 => gpio_ports.pins[0][1].as_ref().unwrap(), // A1
353            12 => gpio_ports.pins[0][2].as_ref().unwrap(), // A2
354            13 => gpio_ports.pins[0][3].as_ref().unwrap(), // A3
355            14 => gpio_ports.pins[0][4].as_ref().unwrap(), // A4
356            15 => gpio_ports.pins[0][5].as_ref().unwrap(), // A5
357            16 => gpio_ports.pins[0][6].as_ref().unwrap(), // A6
358            17 => gpio_ports.pins[0][7].as_ref().unwrap(), // A7
359            18 => gpio_ports.pins[1][0].as_ref().unwrap(), // B0
360            19 => gpio_ports.pins[1][1].as_ref().unwrap(), // B1
361            20 => gpio_ports.pins[1][2].as_ref().unwrap(), // B2
362            21 => gpio_ports.pins[1][10].as_ref().unwrap(), // B10
363            25 => gpio_ports.pins[1][12].as_ref().unwrap(), // B12
364            26 => gpio_ports.pins[1][13].as_ref().unwrap(), // B13
365            27 => gpio_ports.pins[1][14].as_ref().unwrap(), // B14
366            28 => gpio_ports.pins[1][15].as_ref().unwrap(), // B15
367            29 => gpio_ports.pins[0][8].as_ref().unwrap(), // A8
368            30 => gpio_ports.pins[0][9].as_ref().unwrap(), // A9
369            31 => gpio_ports.pins[0][10].as_ref().unwrap(), // A10
370            32 => gpio_ports.pins[0][11].as_ref().unwrap(), // A11
371            33 => gpio_ports.pins[0][12].as_ref().unwrap(), // A12
372            34 => gpio_ports.pins[0][13].as_ref().unwrap(), // A13
373            37 => gpio_ports.pins[0][14].as_ref().unwrap(), // A14
374            38 => gpio_ports.pins[0][15].as_ref().unwrap(), // A15
375            39 => gpio_ports.pins[1][3].as_ref().unwrap(), // B3
376            40 => gpio_ports.pins[1][4].as_ref().unwrap(), // B4
377            41 => gpio_ports.pins[1][5].as_ref().unwrap(), // B5
378            42 => gpio_ports.pins[1][6].as_ref().unwrap(), // B6
379            43 => gpio_ports.pins[1][7].as_ref().unwrap(), // B7
380            45 => gpio_ports.pins[1][8].as_ref().unwrap(), // B8
381            46 => gpio_ports.pins[1][9].as_ref().unwrap(), // B9
382        ),
383    )
384    .finalize(components::gpio_component_static!(stm32f401cc::gpio::Pin));
385
386    // ADC
387    let adc_mux = components::adc::AdcMuxComponent::new(&base_peripherals.adc1)
388        .finalize(components::adc_mux_component_static!(stm32f401cc::adc::Adc));
389
390    let adc_channel_0 =
391        components::adc::AdcComponent::new(adc_mux, stm32f401cc::adc::Channel::Channel3)
392            .finalize(components::adc_component_static!(stm32f401cc::adc::Adc));
393
394    let adc_channel_1 =
395        components::adc::AdcComponent::new(adc_mux, stm32f401cc::adc::Channel::Channel10)
396            .finalize(components::adc_component_static!(stm32f401cc::adc::Adc));
397
398    let adc_channel_2 =
399        components::adc::AdcComponent::new(adc_mux, stm32f401cc::adc::Channel::Channel13)
400            .finalize(components::adc_component_static!(stm32f401cc::adc::Adc));
401
402    let adc_channel_3 =
403        components::adc::AdcComponent::new(adc_mux, stm32f401cc::adc::Channel::Channel9)
404            .finalize(components::adc_component_static!(stm32f401cc::adc::Adc));
405
406    let adc_channel_4 =
407        components::adc::AdcComponent::new(adc_mux, stm32f401cc::adc::Channel::Channel15)
408            .finalize(components::adc_component_static!(stm32f401cc::adc::Adc));
409
410    let adc_channel_5 =
411        components::adc::AdcComponent::new(adc_mux, stm32f401cc::adc::Channel::Channel8)
412            .finalize(components::adc_component_static!(stm32f401cc::adc::Adc));
413
414    let adc_syscall =
415        components::adc::AdcVirtualComponent::new(board_kernel, capsules_core::adc::DRIVER_NUM)
416            .finalize(components::adc_syscall_component_helper!(
417                adc_channel_0,
418                adc_channel_1,
419                adc_channel_2,
420                adc_channel_3,
421                adc_channel_4,
422                adc_channel_5
423            ));
424
425    let process_printer = components::process_printer::ProcessPrinterTextComponent::new()
426        .finalize(components::process_printer_text_component_static!());
427    PROCESS_PRINTER = Some(process_printer);
428
429    // PROCESS CONSOLE
430    let process_console = components::process_console::ProcessConsoleComponent::new(
431        board_kernel,
432        uart_mux,
433        mux_alarm,
434        process_printer,
435        Some(cortexm4::support::reset),
436    )
437    .finalize(components::process_console_component_static!(
438        stm32f401cc::tim2::Tim2
439    ));
440    let _ = process_console.start();
441
442    let scheduler = components::sched::round_robin::RoundRobinComponent::new(processes)
443        .finalize(components::round_robin_component_static!(NUM_PROCS));
444
445    let weact_f401cc = WeactF401CC {
446        console,
447        ipc: kernel::ipc::IPC::new(
448            board_kernel,
449            kernel::ipc::DRIVER_NUM,
450            &memory_allocation_capability,
451        ),
452        adc: adc_syscall,
453        led,
454        button,
455        alarm,
456        gpio,
457        scheduler,
458        systick: cortexm4::systick::SysTick::new_with_calibration(
459            (HSI_FREQUENCY_MHZ * 1_000_000) as u32,
460        ),
461    };
462
463    debug!("Initialization complete. Entering main loop");
464
465    // These symbols are defined in the linker script.
466    extern "C" {
467        /// Beginning of the ROM region containing app images.
468        static _sapps: u8;
469        /// End of the ROM region containing app images.
470        static _eapps: u8;
471        /// Beginning of the RAM region for app memory.
472        static mut _sappmem: u8;
473        /// End of the RAM region for app memory.
474        static _eappmem: u8;
475    }
476
477    kernel::process::load_processes(
478        board_kernel,
479        chip,
480        core::slice::from_raw_parts(
481            core::ptr::addr_of!(_sapps),
482            core::ptr::addr_of!(_eapps) as usize - core::ptr::addr_of!(_sapps) as usize,
483        ),
484        core::slice::from_raw_parts_mut(
485            core::ptr::addr_of_mut!(_sappmem),
486            core::ptr::addr_of!(_eappmem) as usize - core::ptr::addr_of!(_sappmem) as usize,
487        ),
488        &FAULT_RESPONSE,
489        &process_management_capability,
490    )
491    .unwrap_or_else(|err| {
492        debug!("Error loading processes!");
493        debug!("{:?}", err);
494    });
495
496    //Uncomment to run multi alarm test
497    /*components::test::multi_alarm_test::MultiAlarmTestComponent::new(mux_alarm)
498    .finalize(components::multi_alarm_test_component_buf!(stm32f401cc::tim2::Tim2))
499    .run();*/
500
501    (board_kernel, weact_f401cc, chip)
502}
503
504/// Main function called after RAM initialized.
505#[no_mangle]
506pub unsafe fn main() {
507    let main_loop_capability = create_capability!(capabilities::MainLoopCapability);
508
509    let (board_kernel, platform, chip) = start();
510    board_kernel.kernel_loop(&platform, chip, Some(&platform.ipc), &main_loop_capability);
511}