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::hil::led::LedLow;
77use kernel::hil::time::Counter;
78use kernel::platform::{KernelResources, SyscallDriverLookup};
79use kernel::process::ProcessArray;
80use kernel::scheduler::round_robin::RoundRobinSched;
81#[allow(unused_imports)]
82use kernel::{capabilities, create_capability, debug, debug_gpio, debug_verbose, static_init};
83use nrf52832::gpio::Pin;
84use nrf52832::interrupt_service::Nrf52832DefaultPeripherals;
85use nrf52832::rtc::Rtc;
86use nrf52_components::{UartChannel, UartPins};
87
88// The nRF52 DK LEDs (see back of board)
89const LED1_PIN: Pin = Pin::P0_17;
90const LED2_PIN: Pin = Pin::P0_18;
91const LED3_PIN: Pin = Pin::P0_19;
92const LED4_PIN: Pin = Pin::P0_20;
93
94// The nRF52 DK buttons (see back of board)
95const BUTTON1_PIN: Pin = Pin::P0_13;
96const BUTTON2_PIN: Pin = Pin::P0_14;
97const BUTTON3_PIN: Pin = Pin::P0_15;
98const BUTTON4_PIN: Pin = Pin::P0_16;
99const BUTTON_RST_PIN: Pin = Pin::P0_21;
100
101const UART_RTS: Option<Pin> = Some(Pin::P0_05);
102const UART_TXD: Pin = Pin::P0_06;
103const UART_CTS: Option<Pin> = Some(Pin::P0_07);
104const UART_RXD: Pin = Pin::P0_08;
105
106// SPI not used, but keep pins around
107const _SPI_MOSI: Pin = Pin::P0_22;
108const _SPI_MISO: Pin = Pin::P0_23;
109const _SPI_CLK: Pin = Pin::P0_24;
110
111/// UART Writer
112pub mod io;
113
114// FIXME: Ideally this should be replaced with Rust's builtin tests by conditional compilation
115//
116// Also read the instructions in `tests` how to run the tests
117#[allow(dead_code)]
118mod tests;
119
120// State for loading and holding applications.
121// How should the kernel respond when a process faults.
122const FAULT_RESPONSE: capsules_system::process_policies::PanicFaultPolicy =
123    capsules_system::process_policies::PanicFaultPolicy {};
124
125// Number of concurrent processes this platform supports.
126const NUM_PROCS: usize = 4;
127
128type ChipHw = nrf52832::chip::NRF52<'static, Nrf52832DefaultPeripherals<'static>>;
129
130/// Static variables used by io.rs.
131static mut PROCESSES: Option<&'static ProcessArray<NUM_PROCS>> = None;
132static mut CHIP: Option<&'static nrf52832::chip::NRF52<Nrf52832DefaultPeripherals>> = None;
133static mut PROCESS_PRINTER: Option<&'static capsules_system::process_printer::ProcessPrinterText> =
134    None;
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    let nrf52832_peripherals = static_init!(
248        Nrf52832DefaultPeripherals,
249        Nrf52832DefaultPeripherals::new()
250    );
251
252    // set up circular peripheral dependencies
253    nrf52832_peripherals.init();
254    let base_peripherals = &nrf52832_peripherals.nrf52;
255
256    // Create an array to hold process references.
257    let processes = components::process_array::ProcessArrayComponent::new()
258        .finalize(components::process_array_component_static!(NUM_PROCS));
259    PROCESSES = Some(processes);
260
261    // Setup space to store the core kernel data structure.
262    let board_kernel = static_init!(kernel::Kernel, kernel::Kernel::new(processes.as_slice()));
263
264    let gpio = components::gpio::GpioComponent::new(
265        board_kernel,
266        capsules_core::gpio::DRIVER_NUM,
267        components::gpio_component_helper!(
268            nrf52832::gpio::GPIOPin,
269            // Bottom right header on DK board
270            0 => &nrf52832_peripherals.gpio_port[Pin::P0_03],
271            1 => &nrf52832_peripherals.gpio_port[Pin::P0_04],
272            2 => &nrf52832_peripherals.gpio_port[Pin::P0_28],
273            3 => &nrf52832_peripherals.gpio_port[Pin::P0_29],
274            4 => &nrf52832_peripherals.gpio_port[Pin::P0_30],
275            5 => &nrf52832_peripherals.gpio_port[Pin::P0_31],
276            // Top mid header on DK board
277            6 => &nrf52832_peripherals.gpio_port[Pin::P0_12],
278            7 => &nrf52832_peripherals.gpio_port[Pin::P0_11],
279            // Top left header on DK board
280            8 => &nrf52832_peripherals.gpio_port[Pin::P0_27],
281            9 => &nrf52832_peripherals.gpio_port[Pin::P0_26],
282            10 => &nrf52832_peripherals.gpio_port[Pin::P0_02],
283            11 => &nrf52832_peripherals.gpio_port[Pin::P0_25]
284        ),
285    )
286    .finalize(components::gpio_component_static!(nrf52832::gpio::GPIOPin));
287
288    let button = components::button::ButtonComponent::new(
289        board_kernel,
290        capsules_core::button::DRIVER_NUM,
291        components::button_component_helper!(
292            nrf52832::gpio::GPIOPin,
293            (
294                &nrf52832_peripherals.gpio_port[BUTTON1_PIN],
295                kernel::hil::gpio::ActivationMode::ActiveLow,
296                kernel::hil::gpio::FloatingState::PullUp
297            ), //13
298            (
299                &nrf52832_peripherals.gpio_port[BUTTON2_PIN],
300                kernel::hil::gpio::ActivationMode::ActiveLow,
301                kernel::hil::gpio::FloatingState::PullUp
302            ), //14
303            (
304                &nrf52832_peripherals.gpio_port[BUTTON3_PIN],
305                kernel::hil::gpio::ActivationMode::ActiveLow,
306                kernel::hil::gpio::FloatingState::PullUp
307            ), //15
308            (
309                &nrf52832_peripherals.gpio_port[BUTTON4_PIN],
310                kernel::hil::gpio::ActivationMode::ActiveLow,
311                kernel::hil::gpio::FloatingState::PullUp
312            ) //16
313        ),
314    )
315    .finalize(components::button_component_static!(
316        nrf52832::gpio::GPIOPin
317    ));
318
319    let led = components::led::LedsComponent::new().finalize(components::led_component_static!(
320        LedLow<'static, nrf52832::gpio::GPIOPin>,
321        LedLow::new(&nrf52832_peripherals.gpio_port[LED1_PIN]),
322        LedLow::new(&nrf52832_peripherals.gpio_port[LED2_PIN]),
323        LedLow::new(&nrf52832_peripherals.gpio_port[LED3_PIN]),
324        LedLow::new(&nrf52832_peripherals.gpio_port[LED4_PIN]),
325    ));
326
327    let chip = static_init!(
328        nrf52832::chip::NRF52<Nrf52832DefaultPeripherals>,
329        nrf52832::chip::NRF52::new(nrf52832_peripherals)
330    );
331    CHIP = Some(chip);
332
333    nrf52_components::startup::NrfStartupComponent::new(
334        false,
335        BUTTON_RST_PIN,
336        nrf52832::uicr::Regulator0Output::DEFAULT,
337        &base_peripherals.nvmc,
338    )
339    .finalize(());
340
341    // Create capabilities that the board needs to call certain protected kernel
342    // functions.
343    let process_management_capability =
344        create_capability!(capabilities::ProcessManagementCapability);
345    let memory_allocation_capability = create_capability!(capabilities::MemoryAllocationCapability);
346
347    let gpio_port = &nrf52832_peripherals.gpio_port;
348    // Configure kernel debug gpios as early as possible
349    kernel::debug::assign_gpios(
350        Some(&gpio_port[LED1_PIN]),
351        Some(&gpio_port[LED2_PIN]),
352        Some(&gpio_port[LED3_PIN]),
353    );
354
355    let rtc = &base_peripherals.rtc;
356    let _ = rtc.start();
357    let mux_alarm = components::alarm::AlarmMuxComponent::new(rtc)
358        .finalize(components::alarm_mux_component_static!(nrf52832::rtc::Rtc));
359    let alarm = components::alarm::AlarmDriverComponent::new(
360        board_kernel,
361        capsules_core::alarm::DRIVER_NUM,
362        mux_alarm,
363    )
364    .finalize(components::alarm_component_static!(nrf52832::rtc::Rtc));
365    let uart_channel = UartChannel::Pins(UartPins::new(UART_RTS, UART_TXD, UART_CTS, UART_RXD));
366    let channel = nrf52_components::UartChannelComponent::new(
367        uart_channel,
368        mux_alarm,
369        &base_peripherals.uarte0,
370    )
371    .finalize(nrf52_components::uart_channel_component_static!(
372        nrf52832::rtc::Rtc
373    ));
374
375    let process_printer = components::process_printer::ProcessPrinterTextComponent::new()
376        .finalize(components::process_printer_text_component_static!());
377    PROCESS_PRINTER = Some(process_printer);
378
379    // Create a shared UART channel for the console and for kernel debug.
380    let uart_mux = components::console::UartMuxComponent::new(channel, 115200)
381        .finalize(components::uart_mux_component_static!());
382
383    let pconsole = components::process_console::ProcessConsoleComponent::new(
384        board_kernel,
385        uart_mux,
386        mux_alarm,
387        process_printer,
388        Some(cortexm4::support::reset),
389    )
390    .finalize(components::process_console_component_static!(Rtc<'static>));
391
392    // Setup the console.
393    let console = components::console::ConsoleComponent::new(
394        board_kernel,
395        capsules_core::console::DRIVER_NUM,
396        uart_mux,
397    )
398    .finalize(components::console_component_static!());
399    // Create the debugger object that handles calls to `debug!()`.
400    components::debug_writer::DebugWriterComponent::new::<
401        <ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider,
402    >(
403        uart_mux,
404        create_capability!(capabilities::SetDebugWriterCapability),
405    )
406    .finalize(components::debug_writer_component_static!());
407
408    let ble_radio = components::ble::BLEComponent::new(
409        board_kernel,
410        capsules_extra::ble_advertising_driver::DRIVER_NUM,
411        &base_peripherals.ble_radio,
412        mux_alarm,
413    )
414    .finalize(components::ble_component_static!(
415        nrf52832::rtc::Rtc,
416        nrf52832::ble_radio::Radio
417    ));
418
419    let temp = components::temperature::TemperatureComponent::new(
420        board_kernel,
421        capsules_extra::temperature::DRIVER_NUM,
422        &base_peripherals.temp,
423    )
424    .finalize(components::temperature_component_static!(
425        nrf52832::temperature::Temp
426    ));
427
428    let rng = components::rng::RngComponent::new(
429        board_kernel,
430        capsules_core::rng::DRIVER_NUM,
431        &base_peripherals.trng,
432    )
433    .finalize(components::rng_component_static!(nrf52832::trng::Trng));
434
435    // Initialize AC using AIN5 (P0.29) as VIN+ and VIN- as AIN0 (P0.02)
436    // These are hardcoded pin assignments specified in the driver
437    let analog_comparator_channel = static_init!(
438        nrf52832::acomp::Channel,
439        nrf52832::acomp::Channel::new(nrf52832::acomp::ChannelNumber::AC0)
440    );
441    let analog_comparator = components::analog_comparator::AnalogComparatorComponent::new(
442        &base_peripherals.acomp,
443        components::analog_comparator_component_helper!(
444            nrf52832::acomp::Channel,
445            analog_comparator_channel,
446        ),
447        board_kernel,
448        capsules_extra::analog_comparator::DRIVER_NUM,
449    )
450    .finalize(components::analog_comparator_component_static!(
451        nrf52832::acomp::Comparator
452    ));
453
454    nrf52_components::NrfClockComponent::new(&base_peripherals.clock).finalize(());
455
456    let scheduler = components::sched::round_robin::RoundRobinComponent::new(processes)
457        .finalize(components::round_robin_component_static!(NUM_PROCS));
458
459    let platform = Platform {
460        button,
461        ble_radio,
462        pconsole,
463        console,
464        led,
465        gpio,
466        rng,
467        temp,
468        alarm,
469        analog_comparator,
470        ipc: kernel::ipc::IPC::new(
471            board_kernel,
472            kernel::ipc::DRIVER_NUM,
473            &memory_allocation_capability,
474        ),
475        scheduler,
476        systick: cortexm4::systick::SysTick::new_with_calibration(64000000),
477    };
478
479    let _ = platform.pconsole.start();
480    debug!("Initialization complete. Entering main loop\r");
481    debug!("{}", &*addr_of!(nrf52832::ficr::FICR_INSTANCE));
482
483    // These symbols are defined in the linker script.
484    extern "C" {
485        /// Beginning of the ROM region containing app images.
486        static _sapps: u8;
487        /// End of the ROM region containing app images.
488        static _eapps: u8;
489        /// Beginning of the RAM region for app memory.
490        static mut _sappmem: u8;
491        /// End of the RAM region for app memory.
492        static _eappmem: u8;
493    }
494
495    kernel::process::load_processes(
496        board_kernel,
497        chip,
498        core::slice::from_raw_parts(
499            core::ptr::addr_of!(_sapps),
500            core::ptr::addr_of!(_eapps) as usize - core::ptr::addr_of!(_sapps) as usize,
501        ),
502        core::slice::from_raw_parts_mut(
503            core::ptr::addr_of_mut!(_sappmem),
504            core::ptr::addr_of!(_eappmem) as usize - core::ptr::addr_of!(_sappmem) as usize,
505        ),
506        &FAULT_RESPONSE,
507        &process_management_capability,
508    )
509    .unwrap_or_else(|err| {
510        debug!("Error loading processes!");
511        debug!("{:?}", err);
512    });
513
514    (board_kernel, platform, chip)
515}
516
517/// Main function called after RAM initialized.
518#[no_mangle]
519pub unsafe fn main() {
520    let main_loop_capability = create_capability!(capabilities::MainLoopCapability);
521
522    let (board_kernel, platform, chip) = start();
523    board_kernel.kernel_loop(&platform, chip, Some(&platform.ipc), &main_loop_capability);
524}