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
46/// Dummy buffer that causes the linker to reserve enough space for the stack.
47#[no_mangle]
48#[link_section = ".stack_buffer"]
49static mut STACK_MEMORY: [u8; 0x2000] = [0; 0x2000];
50
51/// A structure representing this platform that holds references to all
52/// capsules for this platform.
53struct WeactF401CC {
54    console: &'static capsules_core::console::Console<'static>,
55    ipc: kernel::ipc::IPC<{ NUM_PROCS as u8 }>,
56    led: &'static capsules_core::led::LedDriver<
57        'static,
58        LedLow<'static, stm32f401cc::gpio::Pin<'static>>,
59        1,
60    >,
61    button: &'static capsules_core::button::Button<'static, stm32f401cc::gpio::Pin<'static>>,
62    adc: &'static capsules_core::adc::AdcVirtualized<'static>,
63    alarm: &'static capsules_core::alarm::AlarmDriver<
64        'static,
65        VirtualMuxAlarm<'static, stm32f401cc::tim2::Tim2<'static>>,
66    >,
67    gpio: &'static capsules_core::gpio::GPIO<'static, stm32f401cc::gpio::Pin<'static>>,
68    scheduler: &'static RoundRobinSched<'static>,
69    systick: cortexm4::systick::SysTick,
70}
71
72/// Mapping of integer syscalls to objects that implement syscalls.
73impl SyscallDriverLookup for WeactF401CC {
74    fn with_driver<F, R>(&self, driver_num: usize, f: F) -> R
75    where
76        F: FnOnce(Option<&dyn kernel::syscall::SyscallDriver>) -> R,
77    {
78        match driver_num {
79            capsules_core::console::DRIVER_NUM => f(Some(self.console)),
80            capsules_core::led::DRIVER_NUM => f(Some(self.led)),
81            capsules_core::button::DRIVER_NUM => f(Some(self.button)),
82            capsules_core::adc::DRIVER_NUM => f(Some(self.adc)),
83            capsules_core::alarm::DRIVER_NUM => f(Some(self.alarm)),
84            kernel::ipc::DRIVER_NUM => f(Some(&self.ipc)),
85            capsules_core::gpio::DRIVER_NUM => f(Some(self.gpio)),
86            _ => f(None),
87        }
88    }
89}
90
91impl KernelResources<stm32f401cc::chip::Stm32f4xx<'static, Stm32f401ccDefaultPeripherals<'static>>>
92    for WeactF401CC
93{
94    type SyscallDriverLookup = Self;
95    type SyscallFilter = ();
96    type ProcessFault = ();
97    type Scheduler = RoundRobinSched<'static>;
98    type SchedulerTimer = cortexm4::systick::SysTick;
99    type WatchDog = ();
100    type ContextSwitchCallback = ();
101
102    fn syscall_driver_lookup(&self) -> &Self::SyscallDriverLookup {
103        self
104    }
105    fn syscall_filter(&self) -> &Self::SyscallFilter {
106        &()
107    }
108    fn process_fault(&self) -> &Self::ProcessFault {
109        &()
110    }
111    fn scheduler(&self) -> &Self::Scheduler {
112        self.scheduler
113    }
114    fn scheduler_timer(&self) -> &Self::SchedulerTimer {
115        &self.systick
116    }
117    fn watchdog(&self) -> &Self::WatchDog {
118        &()
119    }
120    fn context_switch_callback(&self) -> &Self::ContextSwitchCallback {
121        &()
122    }
123}
124
125/// Helper function called during bring-up that configures DMA.
126unsafe fn setup_dma(
127    dma: &stm32f401cc::dma::Dma1,
128    dma_streams: &'static [stm32f401cc::dma::Stream<stm32f401cc::dma::Dma1>; 8],
129    usart2: &'static stm32f401cc::usart::Usart<stm32f401cc::dma::Dma1>,
130) {
131    use stm32f401cc::dma::Dma1Peripheral;
132    use stm32f401cc::usart;
133
134    dma.enable_clock();
135
136    let usart2_tx_stream = &dma_streams[Dma1Peripheral::USART2_TX.get_stream_idx()];
137    let usart2_rx_stream = &dma_streams[Dma1Peripheral::USART2_RX.get_stream_idx()];
138
139    usart2.set_dma(
140        usart::TxDMA(usart2_tx_stream),
141        usart::RxDMA(usart2_rx_stream),
142    );
143
144    usart2_tx_stream.set_client(usart2);
145    usart2_rx_stream.set_client(usart2);
146
147    usart2_tx_stream.setup(Dma1Peripheral::USART2_TX);
148    usart2_rx_stream.setup(Dma1Peripheral::USART2_RX);
149
150    cortexm4::nvic::Nvic::new(Dma1Peripheral::USART2_TX.get_stream_irqn()).enable();
151    cortexm4::nvic::Nvic::new(Dma1Peripheral::USART2_RX.get_stream_irqn()).enable();
152}
153
154/// Helper function called during bring-up that configures multiplexed I/O.
155unsafe fn set_pin_primary_functions(
156    syscfg: &stm32f401cc::syscfg::Syscfg,
157    gpio_ports: &'static stm32f401cc::gpio::GpioPorts<'static>,
158) {
159    use kernel::hil::gpio::Configure;
160    use stm32f401cc::gpio::{AlternateFunction, Mode, PinId, PortId};
161
162    syscfg.enable_clock();
163
164    gpio_ports.get_port_from_port_id(PortId::A).enable_clock();
165
166    // On-board KEY button is connected on PA0
167    gpio_ports.get_pin(PinId::PA00).map(|pin| {
168        pin.enable_interrupt();
169    });
170
171    // enable interrupt for D3
172    gpio_ports.get_pin(PinId::PC14).map(|pin| {
173        pin.enable_interrupt();
174    });
175
176    // PA2 (tx) and PA3 (rx) (USART2)
177    gpio_ports.get_pin(PinId::PA02).map(|pin| {
178        pin.set_mode(Mode::AlternateFunctionMode);
179        // AF7 is USART2_TX
180        pin.set_alternate_function(AlternateFunction::AF7);
181    });
182    gpio_ports.get_pin(PinId::PA03).map(|pin| {
183        pin.set_mode(Mode::AlternateFunctionMode);
184        // AF7 is USART2_RX
185        pin.set_alternate_function(AlternateFunction::AF7);
186    });
187
188    gpio_ports.get_port_from_port_id(PortId::C).enable_clock();
189
190    // On-board LED C13 is connected to PC13. Configure PC13 as `debug_gpio!(0, ...)`
191    gpio_ports.get_pin(PinId::PC13).map(|pin| {
192        pin.make_output();
193        // Configure kernel debug gpios as early as possible
194        kernel::debug::assign_gpios(Some(pin), None, None);
195    });
196
197    // Enable clocks for GPIO Ports
198    // Ports A and C enabled above, Port B is the only other board-exposed port
199    gpio_ports.get_port_from_port_id(PortId::B).enable_clock();
200}
201
202/// Helper function for miscellaneous peripheral functions
203unsafe fn setup_peripherals(tim2: &stm32f401cc::tim2::Tim2) {
204    // USART2 IRQn is 37
205    cortexm4::nvic::Nvic::new(stm32f401cc::nvic::USART2).enable();
206
207    // TIM2 IRQn is 28
208    tim2.enable_clock();
209    tim2.start();
210    cortexm4::nvic::Nvic::new(stm32f401cc::nvic::TIM2).enable();
211}
212
213/// Main function
214///
215/// This is in a separate, inline(never) function so that its stack frame is
216/// removed when this function returns. Otherwise, the stack space used for
217/// these static_inits is wasted.
218#[inline(never)]
219unsafe fn start() -> (
220    &'static kernel::Kernel,
221    WeactF401CC,
222    &'static stm32f401cc::chip::Stm32f4xx<'static, Stm32f401ccDefaultPeripherals<'static>>,
223) {
224    stm32f401cc::init();
225
226    // We use the default HSI 16Mhz clock
227    let rcc = static_init!(stm32f401cc::rcc::Rcc, stm32f401cc::rcc::Rcc::new());
228    let clocks = static_init!(
229        stm32f401cc::clocks::Clocks<Stm32f401Specs>,
230        stm32f401cc::clocks::Clocks::new(rcc)
231    );
232    let syscfg = static_init!(
233        stm32f401cc::syscfg::Syscfg,
234        stm32f401cc::syscfg::Syscfg::new(clocks)
235    );
236    let exti = static_init!(
237        stm32f401cc::exti::Exti,
238        stm32f401cc::exti::Exti::new(syscfg)
239    );
240    let dma1 = static_init!(stm32f401cc::dma::Dma1, stm32f401cc::dma::Dma1::new(clocks));
241    let dma2 = static_init!(stm32f401cc::dma::Dma2, stm32f401cc::dma::Dma2::new(clocks));
242
243    let peripherals = static_init!(
244        Stm32f401ccDefaultPeripherals,
245        Stm32f401ccDefaultPeripherals::new(clocks, exti, dma1, dma2)
246    );
247
248    peripherals.init();
249    let base_peripherals = &peripherals.stm32f4;
250
251    setup_peripherals(&base_peripherals.tim2);
252
253    set_pin_primary_functions(syscfg, &base_peripherals.gpio_ports);
254
255    setup_dma(
256        dma1,
257        &base_peripherals.dma1_streams,
258        &base_peripherals.usart2,
259    );
260
261    // Create an array to hold process references.
262    let processes = components::process_array::ProcessArrayComponent::new()
263        .finalize(components::process_array_component_static!(NUM_PROCS));
264    PROCESSES = Some(processes);
265
266    // Setup space to store the core kernel data structure.
267    let board_kernel = static_init!(kernel::Kernel, kernel::Kernel::new(processes.as_slice()));
268
269    let chip = static_init!(
270        stm32f401cc::chip::Stm32f4xx<Stm32f401ccDefaultPeripherals>,
271        stm32f401cc::chip::Stm32f4xx::new(peripherals)
272    );
273    CHIP = Some(chip);
274
275    // UART
276
277    // Create a shared UART channel for kernel debug.
278    base_peripherals.usart2.enable_clock();
279    let uart_mux = components::console::UartMuxComponent::new(&base_peripherals.usart2, 115200)
280        .finalize(components::uart_mux_component_static!());
281
282    (*addr_of_mut!(io::WRITER)).set_initialized();
283
284    // Create capabilities that the board needs to call certain protected kernel
285    // functions.
286    let memory_allocation_capability = create_capability!(capabilities::MemoryAllocationCapability);
287    let process_management_capability =
288        create_capability!(capabilities::ProcessManagementCapability);
289
290    // Setup the console.
291    let console = components::console::ConsoleComponent::new(
292        board_kernel,
293        capsules_core::console::DRIVER_NUM,
294        uart_mux,
295    )
296    .finalize(components::console_component_static!());
297    // Create the debugger object that handles calls to `debug!()`.
298    components::debug_writer::DebugWriterComponent::new(
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}