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