nrf52dk/
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//! Tock kernel for the Nordic Semiconductor nRF52 development kit (DK), a.k.a. the PCA10040.
6//!
7//! It is based on nRF52838 SoC (Cortex M4 core with a BLE transceiver) with many exported
8//! I/O and peripherals.
9//!
10//! nRF52838 has only one port and uses pins 0-31!
11//!
12//! Furthermore, there exist another a preview development kit for nRF52840 but it is not supported
13//! yet because unfortunately the pin configuration differ from nRF52-DK whereas nRF52840 uses two
14//! ports where port 0 has 32 pins and port 1 has 16 pins.
15//!
16//! Pin Configuration
17//! -------------------
18//!
19//! ### `GPIOs`
20//! * P0.27 -> (top left header)
21//! * P0.26 -> (top left header)
22//! * P0.02 -> (top left header)
23//! * P0.25 -> (top left header)
24//! * P0.24 -> (top left header)
25//! * P0.23 -> (top left header)
26//! * P0.22 -> (top left header)
27//! * P0.12 -> (top mid header)
28//! * P0.11 -> (top mid header)
29//! * P0.03 -> (bottom right header)
30//! * P0.04 -> (bottom right header)
31//! * P0.28 -> (bottom right header)
32//! * P0.29 -> (bottom right header)
33//! * P0.30 -> (bottom right header)
34//! * P0.31 -> (bottom right header)
35//!
36//! ### `LEDs`
37//! * P0.17 -> LED1
38//! * P0.18 -> LED2
39//! * P0.19 -> LED3
40//! * P0.20 -> LED4
41//!
42//! ### `Buttons`
43//! * P0.13 -> Button1
44//! * P0.14 -> Button2
45//! * P0.15 -> Button3
46//! * P0.16 -> Button4
47//! * P0.21 -> Reset Button
48//!
49//! ### `UART`
50//! * P0.05 -> RTS
51//! * P0.06 -> TXD
52//! * P0.07 -> CTS
53//! * P0.08 -> RXD
54//!
55//! ### `NFC`
56//! * P0.09 -> NFC1
57//! * P0.10 -> NFC2
58//!
59//! ### `LFXO`
60//! * P0.01 -> XL2
61//! * P0.00 -> XL1
62//!
63//! Author
64//! -------------------
65//! * Niklas Adolfsson <niklasadolfsson1@gmail.com>
66//! * July 16, 2017
67
68#![no_std]
69#![no_main]
70#![deny(missing_docs)]
71
72use core::ptr::addr_of;
73
74use capsules_core::virtualizers::virtual_alarm::VirtualMuxAlarm;
75use kernel::component::Component;
76use kernel::debug::PanicResources;
77use kernel::hil::led::LedLow;
78use kernel::hil::time::Counter;
79use kernel::platform::{KernelResources, SyscallDriverLookup};
80use kernel::scheduler::round_robin::RoundRobinSched;
81use kernel::utilities::single_thread_value::SingleThreadValue;
82#[allow(unused_imports)]
83use kernel::{capabilities, create_capability, debug, debug_gpio, debug_verbose, static_init};
84use nrf52832::gpio::Pin;
85use nrf52832::interrupt_service::Nrf52832DefaultPeripherals;
86use nrf52832::rtc::Rtc;
87use nrf52_components::{UartChannel, UartPins};
88
89// The nRF52 DK LEDs (see back of board)
90const LED1_PIN: Pin = Pin::P0_17;
91const LED2_PIN: Pin = Pin::P0_18;
92const LED3_PIN: Pin = Pin::P0_19;
93const LED4_PIN: Pin = Pin::P0_20;
94
95// The nRF52 DK buttons (see back of board)
96const BUTTON1_PIN: Pin = Pin::P0_13;
97const BUTTON2_PIN: Pin = Pin::P0_14;
98const BUTTON3_PIN: Pin = Pin::P0_15;
99const BUTTON4_PIN: Pin = Pin::P0_16;
100const BUTTON_RST_PIN: Pin = Pin::P0_21;
101
102const UART_RTS: Option<Pin> = Some(Pin::P0_05);
103const UART_TXD: Pin = Pin::P0_06;
104const UART_CTS: Option<Pin> = Some(Pin::P0_07);
105const UART_RXD: Pin = Pin::P0_08;
106
107// SPI not used, but keep pins around
108const _SPI_MOSI: Pin = Pin::P0_22;
109const _SPI_MISO: Pin = Pin::P0_23;
110const _SPI_CLK: Pin = Pin::P0_24;
111
112/// UART Writer
113pub mod io;
114
115// FIXME: Ideally this should be replaced with Rust's builtin tests by conditional compilation
116//
117// Also read the instructions in `tests` how to run the tests
118#[allow(dead_code)]
119mod tests;
120
121// State for loading and holding applications.
122// How should the kernel respond when a process faults.
123const FAULT_RESPONSE: capsules_system::process_policies::PanicFaultPolicy =
124    capsules_system::process_policies::PanicFaultPolicy {};
125
126// Number of concurrent processes this platform supports.
127const NUM_PROCS: usize = 4;
128
129type ChipHw = nrf52832::chip::NRF52<'static, Nrf52832DefaultPeripherals<'static>>;
130type ProcessPrinterInUse = capsules_system::process_printer::ProcessPrinterText;
131
132/// Resources for when a board panics used by io.rs.
133static PANIC_RESOURCES: SingleThreadValue<PanicResources<ChipHw, ProcessPrinterInUse>> =
134    SingleThreadValue::new(PanicResources::new());
135
136kernel::stack_size! {0x1000}
137
138type TemperatureDriver =
139    components::temperature::TemperatureComponentType<nrf52832::temperature::Temp<'static>>;
140type RngDriver = components::rng::RngComponentType<nrf52832::trng::Trng<'static>>;
141
142/// Supported drivers by the platform
143pub struct Platform {
144    ble_radio: &'static capsules_extra::ble_advertising_driver::BLE<
145        'static,
146        nrf52832::ble_radio::Radio<'static>,
147        VirtualMuxAlarm<'static, Rtc<'static>>,
148    >,
149    button: &'static capsules_core::button::Button<'static, nrf52832::gpio::GPIOPin<'static>>,
150    pconsole: &'static capsules_core::process_console::ProcessConsole<
151        'static,
152        { capsules_core::process_console::DEFAULT_COMMAND_HISTORY_LEN },
153        VirtualMuxAlarm<'static, Rtc<'static>>,
154        components::process_console::Capability,
155    >,
156    console: &'static capsules_core::console::Console<'static>,
157    gpio: &'static capsules_core::gpio::GPIO<'static, nrf52832::gpio::GPIOPin<'static>>,
158    led: &'static capsules_core::led::LedDriver<
159        'static,
160        LedLow<'static, nrf52832::gpio::GPIOPin<'static>>,
161        4,
162    >,
163    rng: &'static RngDriver,
164    temp: &'static TemperatureDriver,
165    ipc: kernel::ipc::IPC<{ NUM_PROCS as u8 }>,
166    analog_comparator: &'static capsules_extra::analog_comparator::AnalogComparator<
167        'static,
168        nrf52832::acomp::Comparator<'static>,
169    >,
170    alarm: &'static capsules_core::alarm::AlarmDriver<
171        'static,
172        capsules_core::virtualizers::virtual_alarm::VirtualMuxAlarm<
173            'static,
174            nrf52832::rtc::Rtc<'static>,
175        >,
176    >,
177    scheduler: &'static RoundRobinSched<'static>,
178    systick: cortexm4::systick::SysTick,
179}
180
181impl SyscallDriverLookup for Platform {
182    fn with_driver<F, R>(&self, driver_num: usize, f: F) -> R
183    where
184        F: FnOnce(Option<&dyn kernel::syscall::SyscallDriver>) -> R,
185    {
186        match driver_num {
187            capsules_core::console::DRIVER_NUM => f(Some(self.console)),
188            capsules_core::gpio::DRIVER_NUM => f(Some(self.gpio)),
189            capsules_core::alarm::DRIVER_NUM => f(Some(self.alarm)),
190            capsules_core::led::DRIVER_NUM => f(Some(self.led)),
191            capsules_core::button::DRIVER_NUM => f(Some(self.button)),
192            capsules_core::rng::DRIVER_NUM => f(Some(self.rng)),
193            capsules_extra::ble_advertising_driver::DRIVER_NUM => f(Some(self.ble_radio)),
194            capsules_extra::temperature::DRIVER_NUM => f(Some(self.temp)),
195            capsules_extra::analog_comparator::DRIVER_NUM => f(Some(self.analog_comparator)),
196            kernel::ipc::DRIVER_NUM => f(Some(&self.ipc)),
197            _ => f(None),
198        }
199    }
200}
201
202impl KernelResources<nrf52832::chip::NRF52<'static, Nrf52832DefaultPeripherals<'static>>>
203    for Platform
204{
205    type SyscallDriverLookup = Self;
206    type SyscallFilter = ();
207    type ProcessFault = ();
208    type Scheduler = RoundRobinSched<'static>;
209    type SchedulerTimer = cortexm4::systick::SysTick;
210    type WatchDog = ();
211    type ContextSwitchCallback = ();
212
213    fn syscall_driver_lookup(&self) -> &Self::SyscallDriverLookup {
214        self
215    }
216    fn syscall_filter(&self) -> &Self::SyscallFilter {
217        &()
218    }
219    fn process_fault(&self) -> &Self::ProcessFault {
220        &()
221    }
222    fn scheduler(&self) -> &Self::Scheduler {
223        self.scheduler
224    }
225    fn scheduler_timer(&self) -> &Self::SchedulerTimer {
226        &self.systick
227    }
228    fn watchdog(&self) -> &Self::WatchDog {
229        &()
230    }
231    fn context_switch_callback(&self) -> &Self::ContextSwitchCallback {
232        &()
233    }
234}
235
236/// This is in a separate, inline(never) function so that its stack frame is
237/// removed when this function returns. Otherwise, the stack space used for
238/// these static_inits is wasted.
239#[inline(never)]
240pub unsafe fn start() -> (
241    &'static kernel::Kernel,
242    Platform,
243    &'static nrf52832::chip::NRF52<'static, Nrf52832DefaultPeripherals<'static>>,
244) {
245    nrf52832::init();
246
247    // Initialize deferred calls very early.
248    kernel::deferred_call::initialize_deferred_call_state::<
249        <ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider,
250    >();
251
252    // Bind global variables to this thread.
253    PANIC_RESOURCES.bind_to_thread::<<ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider>();
254
255    let nrf52832_peripherals = static_init!(
256        Nrf52832DefaultPeripherals,
257        Nrf52832DefaultPeripherals::new()
258    );
259
260    // set up circular peripheral dependencies
261    nrf52832_peripherals.init();
262    let base_peripherals = &nrf52832_peripherals.nrf52;
263
264    // Create an array to hold process references.
265    let processes = components::process_array::ProcessArrayComponent::new()
266        .finalize(components::process_array_component_static!(NUM_PROCS));
267    PANIC_RESOURCES.get().map(|resources| {
268        resources.processes.put(processes.as_slice());
269    });
270
271    // Setup space to store the core kernel data structure.
272    let board_kernel = static_init!(kernel::Kernel, kernel::Kernel::new(processes.as_slice()));
273
274    let gpio = components::gpio::GpioComponent::new(
275        board_kernel,
276        capsules_core::gpio::DRIVER_NUM,
277        components::gpio_component_helper!(
278            nrf52832::gpio::GPIOPin,
279            // Bottom right header on DK board
280            0 => &nrf52832_peripherals.gpio_port[Pin::P0_03],
281            1 => &nrf52832_peripherals.gpio_port[Pin::P0_04],
282            2 => &nrf52832_peripherals.gpio_port[Pin::P0_28],
283            3 => &nrf52832_peripherals.gpio_port[Pin::P0_29],
284            4 => &nrf52832_peripherals.gpio_port[Pin::P0_30],
285            5 => &nrf52832_peripherals.gpio_port[Pin::P0_31],
286            // Top mid header on DK board
287            6 => &nrf52832_peripherals.gpio_port[Pin::P0_12],
288            7 => &nrf52832_peripherals.gpio_port[Pin::P0_11],
289            // Top left header on DK board
290            8 => &nrf52832_peripherals.gpio_port[Pin::P0_27],
291            9 => &nrf52832_peripherals.gpio_port[Pin::P0_26],
292            10 => &nrf52832_peripherals.gpio_port[Pin::P0_02],
293            11 => &nrf52832_peripherals.gpio_port[Pin::P0_25]
294        ),
295    )
296    .finalize(components::gpio_component_static!(nrf52832::gpio::GPIOPin));
297
298    let button = components::button::ButtonComponent::new(
299        board_kernel,
300        capsules_core::button::DRIVER_NUM,
301        components::button_component_helper!(
302            nrf52832::gpio::GPIOPin,
303            (
304                &nrf52832_peripherals.gpio_port[BUTTON1_PIN],
305                kernel::hil::gpio::ActivationMode::ActiveLow,
306                kernel::hil::gpio::FloatingState::PullUp
307            ), //13
308            (
309                &nrf52832_peripherals.gpio_port[BUTTON2_PIN],
310                kernel::hil::gpio::ActivationMode::ActiveLow,
311                kernel::hil::gpio::FloatingState::PullUp
312            ), //14
313            (
314                &nrf52832_peripherals.gpio_port[BUTTON3_PIN],
315                kernel::hil::gpio::ActivationMode::ActiveLow,
316                kernel::hil::gpio::FloatingState::PullUp
317            ), //15
318            (
319                &nrf52832_peripherals.gpio_port[BUTTON4_PIN],
320                kernel::hil::gpio::ActivationMode::ActiveLow,
321                kernel::hil::gpio::FloatingState::PullUp
322            ) //16
323        ),
324    )
325    .finalize(components::button_component_static!(
326        nrf52832::gpio::GPIOPin
327    ));
328
329    let led = components::led::LedsComponent::new().finalize(components::led_component_static!(
330        LedLow<'static, nrf52832::gpio::GPIOPin>,
331        LedLow::new(&nrf52832_peripherals.gpio_port[LED1_PIN]),
332        LedLow::new(&nrf52832_peripherals.gpio_port[LED2_PIN]),
333        LedLow::new(&nrf52832_peripherals.gpio_port[LED3_PIN]),
334        LedLow::new(&nrf52832_peripherals.gpio_port[LED4_PIN]),
335    ));
336
337    let chip = static_init!(
338        nrf52832::chip::NRF52<Nrf52832DefaultPeripherals>,
339        nrf52832::chip::NRF52::new(nrf52832_peripherals)
340    );
341    PANIC_RESOURCES.get().map(|resources| {
342        resources.chip.put(chip);
343    });
344
345    nrf52_components::startup::NrfStartupComponent::new(
346        false,
347        BUTTON_RST_PIN,
348        nrf52832::uicr::Regulator0Output::DEFAULT,
349        &base_peripherals.nvmc,
350    )
351    .finalize(());
352
353    // Create capabilities that the board needs to call certain protected kernel
354    // functions.
355    let process_management_capability =
356        create_capability!(capabilities::ProcessManagementCapability);
357    let memory_allocation_capability = create_capability!(capabilities::MemoryAllocationCapability);
358
359    let gpio_port = &nrf52832_peripherals.gpio_port;
360    // Configure kernel debug gpios as early as possible
361    let debug_gpios = static_init!(
362        [&'static dyn kernel::hil::gpio::Pin; 3],
363        [
364            &gpio_port[LED1_PIN],
365            &gpio_port[LED2_PIN],
366            &gpio_port[LED3_PIN]
367        ]
368    );
369    kernel::debug::initialize_debug_gpio::<
370        <ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider,
371    >();
372    kernel::debug::assign_gpios(debug_gpios);
373
374    let rtc = &base_peripherals.rtc;
375    let _ = rtc.start();
376    let mux_alarm = components::alarm::AlarmMuxComponent::new(rtc)
377        .finalize(components::alarm_mux_component_static!(nrf52832::rtc::Rtc));
378    let alarm = components::alarm::AlarmDriverComponent::new(
379        board_kernel,
380        capsules_core::alarm::DRIVER_NUM,
381        mux_alarm,
382    )
383    .finalize(components::alarm_component_static!(nrf52832::rtc::Rtc));
384    let uart_channel = UartChannel::Pins(UartPins::new(UART_RTS, UART_TXD, UART_CTS, UART_RXD));
385    let channel = nrf52_components::UartChannelComponent::new(
386        uart_channel,
387        mux_alarm,
388        &base_peripherals.uarte0,
389    )
390    .finalize(nrf52_components::uart_channel_component_static!(
391        nrf52832::rtc::Rtc
392    ));
393
394    let process_printer = components::process_printer::ProcessPrinterTextComponent::new()
395        .finalize(components::process_printer_text_component_static!());
396    PANIC_RESOURCES.get().map(|resources| {
397        resources.printer.put(process_printer);
398    });
399
400    // Create a shared UART channel for the console and for kernel debug.
401    let uart_mux = components::console::UartMuxComponent::new(channel, 115200)
402        .finalize(components::uart_mux_component_static!());
403
404    let pconsole = components::process_console::ProcessConsoleComponent::new(
405        board_kernel,
406        uart_mux,
407        mux_alarm,
408        process_printer,
409        Some(cortexm4::support::reset),
410    )
411    .finalize(components::process_console_component_static!(Rtc<'static>));
412
413    // Setup the console.
414    let console = components::console::ConsoleComponent::new(
415        board_kernel,
416        capsules_core::console::DRIVER_NUM,
417        uart_mux,
418    )
419    .finalize(components::console_component_static!());
420    // Create the debugger object that handles calls to `debug!()`.
421    components::debug_writer::DebugWriterComponent::new::<
422        <ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider,
423    >(
424        uart_mux,
425        create_capability!(capabilities::SetDebugWriterCapability),
426    )
427    .finalize(components::debug_writer_component_static!());
428
429    let ble_radio = components::ble::BLEComponent::new(
430        board_kernel,
431        capsules_extra::ble_advertising_driver::DRIVER_NUM,
432        &base_peripherals.ble_radio,
433        mux_alarm,
434    )
435    .finalize(components::ble_component_static!(
436        nrf52832::rtc::Rtc,
437        nrf52832::ble_radio::Radio
438    ));
439
440    let temp = components::temperature::TemperatureComponent::new(
441        board_kernel,
442        capsules_extra::temperature::DRIVER_NUM,
443        &base_peripherals.temp,
444    )
445    .finalize(components::temperature_component_static!(
446        nrf52832::temperature::Temp
447    ));
448
449    let rng = components::rng::RngComponent::new(
450        board_kernel,
451        capsules_core::rng::DRIVER_NUM,
452        &base_peripherals.trng,
453    )
454    .finalize(components::rng_component_static!(nrf52832::trng::Trng));
455
456    // Initialize AC using AIN5 (P0.29) as VIN+ and VIN- as AIN0 (P0.02)
457    // These are hardcoded pin assignments specified in the driver
458    let analog_comparator_channel = static_init!(
459        nrf52832::acomp::Channel,
460        nrf52832::acomp::Channel::new(nrf52832::acomp::ChannelNumber::AC0)
461    );
462    let analog_comparator = components::analog_comparator::AnalogComparatorComponent::new(
463        &base_peripherals.acomp,
464        components::analog_comparator_component_helper!(
465            nrf52832::acomp::Channel,
466            analog_comparator_channel,
467        ),
468        board_kernel,
469        capsules_extra::analog_comparator::DRIVER_NUM,
470    )
471    .finalize(components::analog_comparator_component_static!(
472        nrf52832::acomp::Comparator
473    ));
474
475    nrf52_components::NrfClockComponent::new(&base_peripherals.clock).finalize(());
476
477    let scheduler = components::sched::round_robin::RoundRobinComponent::new(processes)
478        .finalize(components::round_robin_component_static!(NUM_PROCS));
479
480    let platform = Platform {
481        button,
482        ble_radio,
483        pconsole,
484        console,
485        led,
486        gpio,
487        rng,
488        temp,
489        alarm,
490        analog_comparator,
491        ipc: kernel::ipc::IPC::new(
492            board_kernel,
493            kernel::ipc::DRIVER_NUM,
494            &memory_allocation_capability,
495        ),
496        scheduler,
497        systick: cortexm4::systick::SysTick::new_with_calibration(64000000),
498    };
499
500    let _ = platform.pconsole.start();
501    debug!("Initialization complete. Entering main loop\r");
502    debug!("{}", &*addr_of!(nrf52832::ficr::FICR_INSTANCE));
503
504    // These symbols are defined in the linker script.
505    extern "C" {
506        /// Beginning of the ROM region containing app images.
507        static _sapps: u8;
508        /// End of the ROM region containing app images.
509        static _eapps: u8;
510        /// Beginning of the RAM region for app memory.
511        static mut _sappmem: u8;
512        /// End of the RAM region for app memory.
513        static _eappmem: u8;
514    }
515
516    kernel::process::load_processes(
517        board_kernel,
518        chip,
519        core::slice::from_raw_parts(
520            core::ptr::addr_of!(_sapps),
521            core::ptr::addr_of!(_eapps) as usize - core::ptr::addr_of!(_sapps) as usize,
522        ),
523        core::slice::from_raw_parts_mut(
524            core::ptr::addr_of_mut!(_sappmem),
525            core::ptr::addr_of!(_eappmem) as usize - core::ptr::addr_of!(_sappmem) as usize,
526        ),
527        &FAULT_RESPONSE,
528        &process_management_capability,
529    )
530    .unwrap_or_else(|err| {
531        debug!("Error loading processes!");
532        debug!("{:?}", err);
533    });
534
535    (board_kernel, platform, chip)
536}
537
538/// Main function called after RAM initialized.
539#[no_mangle]
540pub unsafe fn main() {
541    let main_loop_capability = create_capability!(capabilities::MainLoopCapability);
542
543    let (board_kernel, platform, chip) = start();
544    board_kernel.kernel_loop(&platform, chip, Some(&platform.ipc), &main_loop_capability);
545}