nrf52840dk_lib/
lib.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 nRF52840 development kit (DK).
6//!
7//! It is based on nRF52840 SoC (Cortex M4 core with a BLE transceiver) with
8//! many exported I/O and peripherals.
9//!
10//! Pin Configuration
11//! -------------------
12//!
13//! ### `GPIO`
14//!
15//! | #  | Pin   | Ix | Header | Arduino |
16//! |----|-------|----|--------|---------|
17//! | 0  | P1.01 | 33 | P3 1   | D0      |
18//! | 1  | P1.02 | 34 | P3 2   | D1      |
19//! | 2  | P1.03 | 35 | P3 3   | D2      |
20//! | 3  | P1.04 | 36 | P3 4   | D3      |
21//! | 4  | P1.05 | 37 | P3 5   | D4      |
22//! | 5  | P1.06 | 38 | P3 6   | D5      |
23//! | 6  | P1.07 | 39 | P3 7   | D6      |
24//! | 7  | P1.08 | 40 | P3 8   | D7      |
25//! | 8  | P1.10 | 42 | P4 1   | D8      |
26//! | 9  | P1.11 | 43 | P4 2   | D9      |
27//! | 10 | P1.12 | 44 | P4 3   | D10     |
28//! | 11 | P1.13 | 45 | P4 4   | D11     |
29//! | 12 | P1.14 | 46 | P4 5   | D12     |
30//! | 13 | P1.15 | 47 | P4 6   | D13     |
31//! | 14 | P0.26 | 26 | P4 9   | D14     |
32//! | 15 | P0.27 | 27 | P4 10  | D15     |
33//!
34//! ### `GPIO` / Analog Inputs
35//!
36//! | #  | Pin        | Header | Arduino |
37//! |----|------------|--------|---------|
38//! | 16 | P0.03 AIN1 | P2 1   | A0      |
39//! | 17 | P0.04 AIN2 | P2 2   | A1      |
40//! | 18 | P0.28 AIN4 | P2 3   | A2      |
41//! | 19 | P0.29 AIN5 | P2 4   | A3      |
42//! | 20 | P0.30 AIN6 | P2 5   | A4      |
43//! | 21 | P0.31 AIN7 | P2 6   | A5      |
44//! | 22 | P0.02 AIN0 | P4 8   | AVDD    |
45//!
46//! ### Onboard Functions
47//!
48//! | Pin   | Header | Function |
49//! |-------|--------|----------|
50//! | P0.05 | P6 3   | UART RTS |
51//! | P0.06 | P6 4   | UART TXD |
52//! | P0.07 | P6 5   | UART CTS |
53//! | P0.08 | P6 6   | UART RXT |
54//! | P0.11 | P24 1  | Button 1 |
55//! | P0.12 | P24 2  | Button 2 |
56//! | P0.13 | P24 3  | LED 1    |
57//! | P0.14 | P24 4  | LED 2    |
58//! | P0.15 | P24 5  | LED 3    |
59//! | P0.16 | P24 6  | LED 4    |
60//! | P0.18 | P24 8  | Reset    |
61//! | P0.19 | P24 9  | SPI CLK  |
62//! | P0.20 | P24 10 | SPI MOSI |
63//! | P0.21 | P24 11 | SPI MISO |
64//! | P0.22 | P24 12 | SPI CS   |
65//! | P0.24 | P24 14 | Button 3 |
66//! | P0.25 | P24 15 | Button 4 |
67//! | P0.26 | P24 16 | I2C SDA  |
68//! | P0.27 | P24 17 | I2C SCL  |
69
70#![no_std]
71#![deny(missing_docs)]
72
73use core::ptr::addr_of;
74
75use capsules_core::virtualizers::virtual_alarm::{MuxAlarm, VirtualMuxAlarm};
76use capsules_extra::net::ieee802154::MacAddress;
77use capsules_extra::net::ipv6::ip_utils::IPAddr;
78use kernel::component::Component;
79use kernel::hil::led::LedLow;
80use kernel::hil::time::Counter;
81#[allow(unused_imports)]
82use kernel::hil::usb::Client;
83use kernel::platform::{KernelResources, SyscallDriverLookup};
84use kernel::process::ProcessArray;
85use kernel::scheduler::round_robin::RoundRobinSched;
86#[allow(unused_imports)]
87use kernel::{capabilities, create_capability, debug, debug_gpio, debug_verbose, static_init};
88use nrf52840::gpio::Pin;
89use nrf52840::interrupt_service::Nrf52840DefaultPeripherals;
90use nrf52_components::{UartChannel, UartPins};
91
92// The nRF52840DK LEDs (see back of board)
93const LED1_PIN: Pin = Pin::P0_13;
94const LED2_PIN: Pin = Pin::P0_14;
95const LED3_PIN: Pin = Pin::P0_15;
96const LED4_PIN: Pin = Pin::P0_16;
97
98// The nRF52840DK buttons (see back of board)
99const BUTTON1_PIN: Pin = Pin::P0_11;
100const BUTTON2_PIN: Pin = Pin::P0_12;
101const BUTTON3_PIN: Pin = Pin::P0_24;
102const BUTTON4_PIN: Pin = Pin::P0_25;
103const BUTTON_RST_PIN: Pin = Pin::P0_18;
104
105const UART_RTS: Option<Pin> = Some(Pin::P0_05);
106const UART_TXD: Pin = Pin::P0_06;
107const UART_CTS: Option<Pin> = Some(Pin::P0_07);
108const UART_RXD: Pin = Pin::P0_08;
109
110const SPI_MOSI: Pin = Pin::P0_20;
111const SPI_MISO: Pin = Pin::P0_21;
112const SPI_CLK: Pin = Pin::P0_19;
113const SPI_CS: Pin = Pin::P0_22;
114
115const SPI_MX25R6435F_CHIP_SELECT: Pin = Pin::P0_17;
116const SPI_MX25R6435F_WRITE_PROTECT_PIN: Pin = Pin::P0_22;
117const SPI_MX25R6435F_HOLD_PIN: Pin = Pin::P0_23;
118
119/// I2C pins
120const I2C_SDA_PIN: Pin = Pin::P0_26;
121const I2C_SCL_PIN: Pin = Pin::P0_27;
122
123// Constants related to the configuration of the 15.4 network stack
124const PAN_ID: u16 = 0xABCD;
125const DST_MAC_ADDR: capsules_extra::net::ieee802154::MacAddress =
126    capsules_extra::net::ieee802154::MacAddress::Short(49138);
127const DEFAULT_CTX_PREFIX_LEN: u8 = 8; //Length of context for 6LoWPAN compression
128const DEFAULT_CTX_PREFIX: [u8; 16] = [0x0_u8; 16]; //Context for 6LoWPAN Compression
129
130/// Debug Writer
131pub mod io;
132
133// Whether to use UART debugging or Segger RTT (USB) debugging.
134// - Set to false to use UART.
135// - Set to true to use Segger RTT over USB.
136const USB_DEBUGGING: bool = false;
137
138/// This platform's chip type:
139pub type Chip = nrf52840::chip::NRF52<'static, Nrf52840DefaultPeripherals<'static>>;
140
141/// Number of concurrent processes this platform supports.
142pub const NUM_PROCS: usize = 8;
143
144/// Static variables used by io.rs.
145static mut PROCESSES: Option<&'static ProcessArray<NUM_PROCS>> = None;
146static mut CHIP: Option<&'static nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>> = None;
147static mut PROCESS_PRINTER: Option<&'static capsules_system::process_printer::ProcessPrinterText> =
148    None;
149
150/// Dummy buffer that causes the linker to reserve enough space for the stack.
151#[no_mangle]
152#[link_section = ".stack_buffer"]
153static mut STACK_MEMORY: [u8; 0x2000] = [0; 0x2000];
154
155//------------------------------------------------------------------------------
156// SYSCALL DRIVER TYPE DEFINITIONS
157//------------------------------------------------------------------------------
158
159type AlarmDriver = components::alarm::AlarmDriverComponentType<nrf52840::rtc::Rtc<'static>>;
160type RngDriver = components::rng::RngComponentType<nrf52840::trng::Trng<'static>>;
161
162// TicKV
163type Mx25r6435f = components::mx25r6435f::Mx25r6435fComponentType<
164    nrf52840::spi::SPIM<'static>,
165    nrf52840::gpio::GPIOPin<'static>,
166    nrf52840::rtc::Rtc<'static>,
167>;
168const TICKV_PAGE_SIZE: usize =
169    core::mem::size_of::<<Mx25r6435f as kernel::hil::flash::Flash>::Page>();
170type Siphasher24 = components::siphash::Siphasher24ComponentType;
171type TicKVDedicatedFlash =
172    components::tickv::TicKVDedicatedFlashComponentType<Mx25r6435f, Siphasher24, TICKV_PAGE_SIZE>;
173type TicKVKVStore = components::kv::TicKVKVStoreComponentType<
174    TicKVDedicatedFlash,
175    capsules_extra::tickv::TicKVKeyType,
176>;
177type KVStorePermissions = components::kv::KVStorePermissionsComponentType<TicKVKVStore>;
178type VirtualKVPermissions = components::kv::VirtualKVPermissionsComponentType<KVStorePermissions>;
179type KVDriver = components::kv::KVDriverComponentType<VirtualKVPermissions>;
180
181// Temperature
182type TemperatureDriver =
183    components::temperature::TemperatureComponentType<nrf52840::temperature::Temp<'static>>;
184
185// IEEE 802.15.4
186type Ieee802154MacDevice = components::ieee802154::Ieee802154ComponentMacDeviceType<
187    nrf52840::ieee802154_radio::Radio<'static>,
188    nrf52840::aes::AesECB<'static>,
189>;
190/// Userspace 802.15.4 driver with in-kernel packet framing and MAC layer.
191pub type Ieee802154Driver = components::ieee802154::Ieee802154ComponentType<
192    nrf52840::ieee802154_radio::Radio<'static>,
193    nrf52840::aes::AesECB<'static>,
194>;
195
196// EUI64
197/// Userspace EUI64 driver.
198pub type Eui64Driver = components::eui64::Eui64ComponentType;
199
200/// Supported drivers by the platform
201pub struct Platform {
202    ble_radio: &'static capsules_extra::ble_advertising_driver::BLE<
203        'static,
204        nrf52840::ble_radio::Radio<'static>,
205        VirtualMuxAlarm<'static, nrf52840::rtc::Rtc<'static>>,
206    >,
207    button: &'static capsules_core::button::Button<'static, nrf52840::gpio::GPIOPin<'static>>,
208    pconsole: &'static capsules_core::process_console::ProcessConsole<
209        'static,
210        { capsules_core::process_console::DEFAULT_COMMAND_HISTORY_LEN },
211        VirtualMuxAlarm<'static, nrf52840::rtc::Rtc<'static>>,
212        components::process_console::Capability,
213    >,
214    console: &'static capsules_core::console::Console<'static>,
215    gpio: &'static capsules_core::gpio::GPIO<'static, nrf52840::gpio::GPIOPin<'static>>,
216    led: &'static capsules_core::led::LedDriver<
217        'static,
218        kernel::hil::led::LedLow<'static, nrf52840::gpio::GPIOPin<'static>>,
219        4,
220    >,
221    rng: &'static RngDriver,
222    adc: &'static capsules_core::adc::AdcDedicated<'static, nrf52840::adc::Adc<'static>>,
223    temp: &'static TemperatureDriver,
224    /// The IPC driver.
225    pub ipc: kernel::ipc::IPC<{ NUM_PROCS as u8 }>,
226    analog_comparator: &'static capsules_extra::analog_comparator::AnalogComparator<
227        'static,
228        nrf52840::acomp::Comparator<'static>,
229    >,
230    alarm: &'static AlarmDriver,
231    i2c_master_slave: &'static capsules_core::i2c_master_slave_driver::I2CMasterSlaveDriver<
232        'static,
233        nrf52840::i2c::TWI<'static>,
234    >,
235    spi_controller: &'static capsules_core::spi_controller::Spi<
236        'static,
237        capsules_core::virtualizers::virtual_spi::VirtualSpiMasterDevice<
238            'static,
239            nrf52840::spi::SPIM<'static>,
240        >,
241    >,
242    kv_driver: &'static KVDriver,
243    scheduler: &'static RoundRobinSched<'static>,
244    systick: cortexm4::systick::SysTick,
245}
246
247impl SyscallDriverLookup for Platform {
248    fn with_driver<F, R>(&self, driver_num: usize, f: F) -> R
249    where
250        F: FnOnce(Option<&dyn kernel::syscall::SyscallDriver>) -> R,
251    {
252        match driver_num {
253            capsules_core::console::DRIVER_NUM => f(Some(self.console)),
254            capsules_core::gpio::DRIVER_NUM => f(Some(self.gpio)),
255            capsules_core::alarm::DRIVER_NUM => f(Some(self.alarm)),
256            capsules_core::led::DRIVER_NUM => f(Some(self.led)),
257            capsules_core::button::DRIVER_NUM => f(Some(self.button)),
258            capsules_core::rng::DRIVER_NUM => f(Some(self.rng)),
259            capsules_core::adc::DRIVER_NUM => f(Some(self.adc)),
260            capsules_extra::ble_advertising_driver::DRIVER_NUM => f(Some(self.ble_radio)),
261            capsules_extra::temperature::DRIVER_NUM => f(Some(self.temp)),
262            capsules_extra::analog_comparator::DRIVER_NUM => f(Some(self.analog_comparator)),
263            kernel::ipc::DRIVER_NUM => f(Some(&self.ipc)),
264            capsules_core::i2c_master_slave_driver::DRIVER_NUM => f(Some(self.i2c_master_slave)),
265            capsules_core::spi_controller::DRIVER_NUM => f(Some(self.spi_controller)),
266            capsules_extra::kv_driver::DRIVER_NUM => f(Some(self.kv_driver)),
267            _ => f(None),
268        }
269    }
270}
271
272impl KernelResources<Chip> for Platform {
273    type SyscallDriverLookup = Self;
274    type SyscallFilter = ();
275    type ProcessFault = ();
276    type Scheduler = RoundRobinSched<'static>;
277    type SchedulerTimer = cortexm4::systick::SysTick;
278    type WatchDog = ();
279    type ContextSwitchCallback = ();
280
281    fn syscall_driver_lookup(&self) -> &Self::SyscallDriverLookup {
282        self
283    }
284    fn syscall_filter(&self) -> &Self::SyscallFilter {
285        &()
286    }
287    fn process_fault(&self) -> &Self::ProcessFault {
288        &()
289    }
290    fn scheduler(&self) -> &Self::Scheduler {
291        self.scheduler
292    }
293    fn scheduler_timer(&self) -> &Self::SchedulerTimer {
294        &self.systick
295    }
296    fn watchdog(&self) -> &Self::WatchDog {
297        &()
298    }
299    fn context_switch_callback(&self) -> &Self::ContextSwitchCallback {
300        &()
301    }
302}
303
304/// Create the capsules needed for the in-kernel UDP and 15.4 stack.
305pub unsafe fn ieee802154_udp(
306    board_kernel: &'static kernel::Kernel,
307    nrf52840_peripherals: &'static Nrf52840DefaultPeripherals<'static>,
308    mux_alarm: &'static MuxAlarm<nrf52840::rtc::Rtc>,
309) -> (
310    &'static Eui64Driver,
311    &'static Ieee802154Driver,
312    &'static capsules_extra::net::udp::UDPDriver<'static>,
313) {
314    //--------------------------------------------------------------------------
315    // AES
316    //--------------------------------------------------------------------------
317
318    let aes_mux =
319        components::ieee802154::MuxAes128ccmComponent::new(&nrf52840_peripherals.nrf52.ecb)
320            .finalize(components::mux_aes128ccm_component_static!(
321                nrf52840::aes::AesECB
322            ));
323
324    //--------------------------------------------------------------------------
325    // 802.15.4
326    //--------------------------------------------------------------------------
327
328    let device_id = (*addr_of!(nrf52840::ficr::FICR_INSTANCE)).id();
329    let device_id_bottom_16: u16 = u16::from_le_bytes([device_id[0], device_id[1]]);
330
331    let eui64_driver = components::eui64::Eui64Component::new(u64::from_le_bytes(device_id))
332        .finalize(components::eui64_component_static!());
333
334    let (ieee802154_driver, mux_mac) = components::ieee802154::Ieee802154Component::new(
335        board_kernel,
336        capsules_extra::ieee802154::DRIVER_NUM,
337        &nrf52840_peripherals.ieee802154_radio,
338        aes_mux,
339        PAN_ID,
340        device_id_bottom_16,
341        device_id,
342    )
343    .finalize(components::ieee802154_component_static!(
344        nrf52840::ieee802154_radio::Radio,
345        nrf52840::aes::AesECB<'static>
346    ));
347
348    //--------------------------------------------------------------------------
349    // UDP
350    //--------------------------------------------------------------------------
351
352    let local_ip_ifaces = static_init!(
353        [IPAddr; 3],
354        [
355            IPAddr::generate_from_mac(capsules_extra::net::ieee802154::MacAddress::Long(device_id)),
356            IPAddr([
357                0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d,
358                0x1e, 0x1f,
359            ]),
360            IPAddr::generate_from_mac(capsules_extra::net::ieee802154::MacAddress::Short(
361                device_id_bottom_16
362            )),
363        ]
364    );
365
366    let (udp_send_mux, udp_recv_mux, udp_port_table) = components::udp_mux::UDPMuxComponent::new(
367        mux_mac,
368        DEFAULT_CTX_PREFIX_LEN,
369        DEFAULT_CTX_PREFIX,
370        DST_MAC_ADDR,
371        MacAddress::Long(device_id),
372        local_ip_ifaces,
373        mux_alarm,
374    )
375    .finalize(components::udp_mux_component_static!(
376        nrf52840::rtc::Rtc,
377        Ieee802154MacDevice
378    ));
379
380    // UDP driver initialization happens here
381    let udp_driver = components::udp_driver::UDPDriverComponent::new(
382        board_kernel,
383        capsules_extra::net::udp::driver::DRIVER_NUM,
384        udp_send_mux,
385        udp_recv_mux,
386        udp_port_table,
387        local_ip_ifaces,
388    )
389    .finalize(components::udp_driver_component_static!(nrf52840::rtc::Rtc));
390
391    (eui64_driver, ieee802154_driver, udp_driver)
392}
393
394/// This is in a separate, inline(never) function so that its stack frame is
395/// removed when this function returns. Otherwise, the stack space used for
396/// these static_inits is wasted.
397#[inline(never)]
398pub unsafe fn start_no_pconsole() -> (
399    &'static kernel::Kernel,
400    Platform,
401    &'static Chip,
402    &'static Nrf52840DefaultPeripherals<'static>,
403    &'static MuxAlarm<'static, nrf52840::rtc::Rtc<'static>>,
404) {
405    //--------------------------------------------------------------------------
406    // INITIAL SETUP
407    //--------------------------------------------------------------------------
408
409    // Apply errata fixes and enable interrupts.
410    nrf52840::init();
411
412    // Set up peripheral drivers. Called in separate function to reduce stack
413    // usage.
414    let ieee802154_ack_buf = static_init!(
415        [u8; nrf52840::ieee802154_radio::ACK_BUF_SIZE],
416        [0; nrf52840::ieee802154_radio::ACK_BUF_SIZE]
417    );
418    // Initialize chip peripheral drivers
419    let nrf52840_peripherals = static_init!(
420        Nrf52840DefaultPeripherals,
421        Nrf52840DefaultPeripherals::new(ieee802154_ack_buf)
422    );
423
424    // Set up circular peripheral dependencies.
425    nrf52840_peripherals.init();
426    let base_peripherals = &nrf52840_peripherals.nrf52;
427
428    // Configure kernel debug GPIOs as early as possible.
429    kernel::debug::assign_gpios(
430        Some(&nrf52840_peripherals.gpio_port[LED1_PIN]),
431        Some(&nrf52840_peripherals.gpio_port[LED2_PIN]),
432        Some(&nrf52840_peripherals.gpio_port[LED3_PIN]),
433    );
434
435    // Choose the channel for serial output. This board can be configured to use
436    // either the Segger RTT channel or via UART with traditional TX/RX GPIO
437    // pins.
438    let uart_channel = if USB_DEBUGGING {
439        // Initialize early so any panic beyond this point can use the RTT
440        // memory object.
441        let rtt_memory_refs = components::segger_rtt::SeggerRttMemoryComponent::new()
442            .finalize(components::segger_rtt_memory_component_static!());
443
444        // XXX: This is inherently unsafe as it aliases the mutable reference to
445        // rtt_memory. This aliases reference is only used inside a panic
446        // handler, which should be OK, but maybe we should use a const
447        // reference to rtt_memory and leverage interior mutability instead.
448        self::io::set_rtt_memory(&*core::ptr::from_mut(rtt_memory_refs.rtt_memory));
449
450        UartChannel::Rtt(rtt_memory_refs)
451    } else {
452        UartChannel::Pins(UartPins::new(UART_RTS, UART_TXD, UART_CTS, UART_RXD))
453    };
454
455    // Create an array to hold process references.
456    let processes = components::process_array::ProcessArrayComponent::new()
457        .finalize(components::process_array_component_static!(NUM_PROCS));
458    PROCESSES = Some(processes);
459
460    // Setup space to store the core kernel data structure.
461    let board_kernel = static_init!(kernel::Kernel, kernel::Kernel::new(processes.as_slice()));
462
463    // Create (and save for panic debugging) a chip object to setup low-level
464    // resources (e.g. MPU, systick).
465    let chip = static_init!(Chip, nrf52840::chip::NRF52::new(nrf52840_peripherals));
466    CHIP = Some(chip);
467
468    // Do nRF configuration and setup. This is shared code with other nRF-based
469    // platforms.
470    nrf52_components::startup::NrfStartupComponent::new(
471        false,
472        BUTTON_RST_PIN,
473        nrf52840::uicr::Regulator0Output::DEFAULT,
474        &base_peripherals.nvmc,
475    )
476    .finalize(());
477
478    //--------------------------------------------------------------------------
479    // CAPABILITIES
480    //--------------------------------------------------------------------------
481
482    // Create capabilities that the board needs to call certain protected kernel
483    // functions.
484    let memory_allocation_capability = create_capability!(capabilities::MemoryAllocationCapability);
485    let gpio_port = &nrf52840_peripherals.gpio_port;
486
487    //--------------------------------------------------------------------------
488    // GPIO
489    //--------------------------------------------------------------------------
490
491    // Expose the D0-D13 Arduino GPIO pins to userspace.
492    let gpio = components::gpio::GpioComponent::new(
493        board_kernel,
494        capsules_core::gpio::DRIVER_NUM,
495        components::gpio_component_helper!(
496            nrf52840::gpio::GPIOPin,
497            0 => &nrf52840_peripherals.gpio_port[Pin::P1_01],
498            1 => &nrf52840_peripherals.gpio_port[Pin::P1_02],
499            2 => &nrf52840_peripherals.gpio_port[Pin::P1_03],
500            3 => &nrf52840_peripherals.gpio_port[Pin::P1_04],
501            4 => &nrf52840_peripherals.gpio_port[Pin::P1_05],
502            5 => &nrf52840_peripherals.gpio_port[Pin::P1_06],
503            6 => &nrf52840_peripherals.gpio_port[Pin::P1_07],
504            7 => &nrf52840_peripherals.gpio_port[Pin::P1_08],
505            // Avoid exposing the I2C pins to userspace, as these are used in
506            // some tutorials (e.g., `nrf52840dk-thread-tutorial`).
507            //
508            // In the future we might want to make this configurable.
509            //
510            // 8 => &nrf52840_peripherals.gpio_port[Pin::P1_10],
511            // 9 => &nrf52840_peripherals.gpio_port[Pin::P1_11],
512            10 => &nrf52840_peripherals.gpio_port[Pin::P1_12],
513            11 => &nrf52840_peripherals.gpio_port[Pin::P1_13],
514            12 => &nrf52840_peripherals.gpio_port[Pin::P1_14],
515            13 => &nrf52840_peripherals.gpio_port[Pin::P1_15],
516        ),
517    )
518    .finalize(components::gpio_component_static!(nrf52840::gpio::GPIOPin));
519
520    //--------------------------------------------------------------------------
521    // BUTTONS
522    //--------------------------------------------------------------------------
523
524    let button = components::button::ButtonComponent::new(
525        board_kernel,
526        capsules_core::button::DRIVER_NUM,
527        components::button_component_helper!(
528            nrf52840::gpio::GPIOPin,
529            (
530                &nrf52840_peripherals.gpio_port[BUTTON1_PIN],
531                kernel::hil::gpio::ActivationMode::ActiveLow,
532                kernel::hil::gpio::FloatingState::PullUp
533            ),
534            (
535                &nrf52840_peripherals.gpio_port[BUTTON2_PIN],
536                kernel::hil::gpio::ActivationMode::ActiveLow,
537                kernel::hil::gpio::FloatingState::PullUp
538            ),
539            (
540                &nrf52840_peripherals.gpio_port[BUTTON3_PIN],
541                kernel::hil::gpio::ActivationMode::ActiveLow,
542                kernel::hil::gpio::FloatingState::PullUp
543            ),
544            (
545                &nrf52840_peripherals.gpio_port[BUTTON4_PIN],
546                kernel::hil::gpio::ActivationMode::ActiveLow,
547                kernel::hil::gpio::FloatingState::PullUp
548            )
549        ),
550    )
551    .finalize(components::button_component_static!(
552        nrf52840::gpio::GPIOPin
553    ));
554
555    //--------------------------------------------------------------------------
556    // LEDs
557    //--------------------------------------------------------------------------
558
559    let led = components::led::LedsComponent::new().finalize(components::led_component_static!(
560        LedLow<'static, nrf52840::gpio::GPIOPin>,
561        LedLow::new(&nrf52840_peripherals.gpio_port[LED1_PIN]),
562        LedLow::new(&nrf52840_peripherals.gpio_port[LED2_PIN]),
563        LedLow::new(&nrf52840_peripherals.gpio_port[LED3_PIN]),
564        LedLow::new(&nrf52840_peripherals.gpio_port[LED4_PIN]),
565    ));
566
567    //--------------------------------------------------------------------------
568    // TIMER
569    //--------------------------------------------------------------------------
570
571    let rtc = &base_peripherals.rtc;
572    let _ = rtc.start();
573    let mux_alarm = components::alarm::AlarmMuxComponent::new(rtc)
574        .finalize(components::alarm_mux_component_static!(nrf52840::rtc::Rtc));
575    let alarm = components::alarm::AlarmDriverComponent::new(
576        board_kernel,
577        capsules_core::alarm::DRIVER_NUM,
578        mux_alarm,
579    )
580    .finalize(components::alarm_component_static!(nrf52840::rtc::Rtc));
581
582    //--------------------------------------------------------------------------
583    // UART & CONSOLE & DEBUG
584    //--------------------------------------------------------------------------
585
586    let uart_channel = nrf52_components::UartChannelComponent::new(
587        uart_channel,
588        mux_alarm,
589        &base_peripherals.uarte0,
590    )
591    .finalize(nrf52_components::uart_channel_component_static!(
592        nrf52840::rtc::Rtc
593    ));
594
595    // Tool for displaying information about processes.
596    let process_printer = components::process_printer::ProcessPrinterTextComponent::new()
597        .finalize(components::process_printer_text_component_static!());
598    PROCESS_PRINTER = Some(process_printer);
599
600    // Virtualize the UART channel for the console and for kernel debug.
601    let uart_mux = components::console::UartMuxComponent::new(uart_channel, 115200)
602        .finalize(components::uart_mux_component_static!());
603
604    // Create the process console, an interactive terminal for managing
605    // processes.
606    let pconsole = components::process_console::ProcessConsoleComponent::new(
607        board_kernel,
608        uart_mux,
609        mux_alarm,
610        process_printer,
611        Some(cortexm4::support::reset),
612    )
613    .finalize(components::process_console_component_static!(
614        nrf52840::rtc::Rtc<'static>
615    ));
616
617    // Setup the serial console for userspace.
618    let console = components::console::ConsoleComponent::new(
619        board_kernel,
620        capsules_core::console::DRIVER_NUM,
621        uart_mux,
622    )
623    .finalize(components::console_component_static!());
624
625    // Create the debugger object that handles calls to `debug!()`.
626    components::debug_writer::DebugWriterComponent::new(
627        uart_mux,
628        create_capability!(capabilities::SetDebugWriterCapability),
629    )
630    .finalize(components::debug_writer_component_static!());
631
632    //--------------------------------------------------------------------------
633    // BLE
634    //--------------------------------------------------------------------------
635
636    let ble_radio = components::ble::BLEComponent::new(
637        board_kernel,
638        capsules_extra::ble_advertising_driver::DRIVER_NUM,
639        &base_peripherals.ble_radio,
640        mux_alarm,
641    )
642    .finalize(components::ble_component_static!(
643        nrf52840::rtc::Rtc,
644        nrf52840::ble_radio::Radio
645    ));
646
647    //--------------------------------------------------------------------------
648    // TEMPERATURE (internal)
649    //--------------------------------------------------------------------------
650
651    let temp = components::temperature::TemperatureComponent::new(
652        board_kernel,
653        capsules_extra::temperature::DRIVER_NUM,
654        &base_peripherals.temp,
655    )
656    .finalize(components::temperature_component_static!(
657        nrf52840::temperature::Temp
658    ));
659
660    //--------------------------------------------------------------------------
661    // RANDOM NUMBER GENERATOR
662    //--------------------------------------------------------------------------
663
664    let rng = components::rng::RngComponent::new(
665        board_kernel,
666        capsules_core::rng::DRIVER_NUM,
667        &base_peripherals.trng,
668    )
669    .finalize(components::rng_component_static!(nrf52840::trng::Trng));
670
671    //--------------------------------------------------------------------------
672    // ADC
673    //--------------------------------------------------------------------------
674
675    let adc_channels = static_init!(
676        [nrf52840::adc::AdcChannelSetup; 6],
677        [
678            nrf52840::adc::AdcChannelSetup::new(nrf52840::adc::AdcChannel::AnalogInput1),
679            nrf52840::adc::AdcChannelSetup::new(nrf52840::adc::AdcChannel::AnalogInput2),
680            nrf52840::adc::AdcChannelSetup::new(nrf52840::adc::AdcChannel::AnalogInput4),
681            nrf52840::adc::AdcChannelSetup::new(nrf52840::adc::AdcChannel::AnalogInput5),
682            nrf52840::adc::AdcChannelSetup::new(nrf52840::adc::AdcChannel::AnalogInput6),
683            nrf52840::adc::AdcChannelSetup::new(nrf52840::adc::AdcChannel::AnalogInput7),
684        ]
685    );
686    let adc = components::adc::AdcDedicatedComponent::new(
687        &base_peripherals.adc,
688        adc_channels,
689        board_kernel,
690        capsules_core::adc::DRIVER_NUM,
691    )
692    .finalize(components::adc_dedicated_component_static!(
693        nrf52840::adc::Adc
694    ));
695
696    //--------------------------------------------------------------------------
697    // SPI
698    //--------------------------------------------------------------------------
699
700    let mux_spi = components::spi::SpiMuxComponent::new(&base_peripherals.spim0)
701        .finalize(components::spi_mux_component_static!(nrf52840::spi::SPIM));
702
703    // Create the SPI system call capsule.
704    let spi_controller = components::spi::SpiSyscallComponent::new(
705        board_kernel,
706        mux_spi,
707        kernel::hil::spi::cs::IntoChipSelect::<_, kernel::hil::spi::cs::ActiveLow>::into_cs(
708            &gpio_port[SPI_CS],
709        ),
710        capsules_core::spi_controller::DRIVER_NUM,
711    )
712    .finalize(components::spi_syscall_component_static!(
713        nrf52840::spi::SPIM
714    ));
715
716    base_peripherals.spim0.configure(
717        nrf52840::pinmux::Pinmux::new(SPI_MOSI as u32),
718        nrf52840::pinmux::Pinmux::new(SPI_MISO as u32),
719        nrf52840::pinmux::Pinmux::new(SPI_CLK as u32),
720    );
721
722    //--------------------------------------------------------------------------
723    // ONBOARD EXTERNAL FLASH
724    //--------------------------------------------------------------------------
725
726    let mx25r6435f = components::mx25r6435f::Mx25r6435fComponent::new(
727        Some(&gpio_port[SPI_MX25R6435F_WRITE_PROTECT_PIN]),
728        Some(&gpio_port[SPI_MX25R6435F_HOLD_PIN]),
729        &gpio_port[SPI_MX25R6435F_CHIP_SELECT],
730        mux_alarm,
731        mux_spi,
732    )
733    .finalize(components::mx25r6435f_component_static!(
734        nrf52840::spi::SPIM,
735        nrf52840::gpio::GPIOPin,
736        nrf52840::rtc::Rtc
737    ));
738
739    //--------------------------------------------------------------------------
740    // TICKV
741    //--------------------------------------------------------------------------
742
743    // Static buffer to use when reading/writing flash for TicKV.
744    let page_buffer = static_init!(
745        <Mx25r6435f as kernel::hil::flash::Flash>::Page,
746        <Mx25r6435f as kernel::hil::flash::Flash>::Page::default()
747    );
748
749    // SipHash for creating TicKV hashed keys.
750    let sip_hash = components::siphash::Siphasher24Component::new()
751        .finalize(components::siphasher24_component_static!());
752
753    // TicKV with Tock wrapper/interface.
754    let tickv = components::tickv::TicKVDedicatedFlashComponent::new(
755        sip_hash,
756        mx25r6435f,
757        0, // start at the beginning of the flash chip
758        (capsules_extra::mx25r6435f::SECTOR_SIZE as usize) * 32, // arbitrary size of 32 pages
759        page_buffer,
760    )
761    .finalize(components::tickv_dedicated_flash_component_static!(
762        Mx25r6435f,
763        Siphasher24,
764        TICKV_PAGE_SIZE,
765    ));
766
767    // KVSystem interface to KV (built on TicKV).
768    let tickv_kv_store = components::kv::TicKVKVStoreComponent::new(tickv).finalize(
769        components::tickv_kv_store_component_static!(
770            TicKVDedicatedFlash,
771            capsules_extra::tickv::TicKVKeyType,
772        ),
773    );
774
775    let kv_store_permissions = components::kv::KVStorePermissionsComponent::new(tickv_kv_store)
776        .finalize(components::kv_store_permissions_component_static!(
777            TicKVKVStore
778        ));
779
780    // Share the KV stack with a mux.
781    let mux_kv = components::kv::KVPermissionsMuxComponent::new(kv_store_permissions).finalize(
782        components::kv_permissions_mux_component_static!(KVStorePermissions),
783    );
784
785    // Create a virtual component for the userspace driver.
786    let virtual_kv_driver = components::kv::VirtualKVPermissionsComponent::new(mux_kv).finalize(
787        components::virtual_kv_permissions_component_static!(KVStorePermissions),
788    );
789
790    // Userspace driver for KV.
791    let kv_driver = components::kv::KVDriverComponent::new(
792        virtual_kv_driver,
793        board_kernel,
794        capsules_extra::kv_driver::DRIVER_NUM,
795    )
796    .finalize(components::kv_driver_component_static!(
797        VirtualKVPermissions
798    ));
799
800    //--------------------------------------------------------------------------
801    // I2C CONTROLLER/TARGET
802    //--------------------------------------------------------------------------
803
804    let i2c_master_slave = components::i2c::I2CMasterSlaveDriverComponent::new(
805        board_kernel,
806        capsules_core::i2c_master_slave_driver::DRIVER_NUM,
807        &base_peripherals.twi1,
808    )
809    .finalize(components::i2c_master_slave_component_static!(
810        nrf52840::i2c::TWI
811    ));
812
813    base_peripherals.twi1.configure(
814        nrf52840::pinmux::Pinmux::new(I2C_SCL_PIN as u32),
815        nrf52840::pinmux::Pinmux::new(I2C_SDA_PIN as u32),
816    );
817    base_peripherals.twi1.set_speed(nrf52840::i2c::Speed::K400);
818
819    //--------------------------------------------------------------------------
820    // ANALOG COMPARATOR
821    //--------------------------------------------------------------------------
822
823    // Initialize AC using AIN5 (P0.29) as VIN+ and VIN- as AIN0 (P0.02)
824    // These are hardcoded pin assignments specified in the driver
825    let analog_comparator = components::analog_comparator::AnalogComparatorComponent::new(
826        &base_peripherals.acomp,
827        components::analog_comparator_component_helper!(
828            nrf52840::acomp::Channel,
829            &*addr_of!(nrf52840::acomp::CHANNEL_AC0)
830        ),
831        board_kernel,
832        capsules_extra::analog_comparator::DRIVER_NUM,
833    )
834    .finalize(components::analog_comparator_component_static!(
835        nrf52840::acomp::Comparator
836    ));
837
838    //--------------------------------------------------------------------------
839    // NRF CLOCK SETUP
840    //--------------------------------------------------------------------------
841
842    nrf52_components::NrfClockComponent::new(&base_peripherals.clock).finalize(());
843
844    //--------------------------------------------------------------------------
845    // USB EXAMPLES
846    //--------------------------------------------------------------------------
847    // Uncomment to experiment with this.
848
849    // // Create the strings we include in the USB descriptor.
850    // let strings = static_init!(
851    //     [&str; 3],
852    //     [
853    //         "Nordic Semiconductor", // Manufacturer
854    //         "nRF52840dk - TockOS",  // Product
855    //         "serial0001",           // Serial number
856    //     ]
857    // );
858
859    // CTAP Example
860    //
861    // let (ctap, _ctap_driver) = components::ctap::CtapComponent::new(
862    //     board_kernel,
863    //     capsules_extra::ctap::DRIVER_NUM,
864    //     &nrf52840_peripherals.usbd,
865    //     0x1915, // Nordic Semiconductor
866    //     0x503a, // lowRISC generic FS USB
867    //     strings,
868    // )
869    // .finalize(components::ctap_component_static!(nrf52840::usbd::Usbd));
870
871    // ctap.enable();
872    // ctap.attach();
873
874    // // Keyboard HID Example
875    // type UsbHw = nrf52840::usbd::Usbd<'static>;
876    // let usb_device = &nrf52840_peripherals.usbd;
877
878    // let (keyboard_hid, keyboard_hid_driver) = components::keyboard_hid::KeyboardHidComponent::new(
879    //     board_kernel,
880    //     capsules_core::driver::NUM::KeyboardHid as usize,
881    //     usb_device,
882    //     0x1915, // Nordic Semiconductor
883    //     0x503a,
884    //     strings,
885    // )
886    // .finalize(components::keyboard_hid_component_static!(UsbHw));
887
888    // keyboard_hid.enable();
889    // keyboard_hid.attach();
890
891    //--------------------------------------------------------------------------
892    // PLATFORM SETUP, SCHEDULER, AND START KERNEL LOOP
893    //--------------------------------------------------------------------------
894
895    let scheduler = components::sched::round_robin::RoundRobinComponent::new(processes)
896        .finalize(components::round_robin_component_static!(NUM_PROCS));
897
898    let platform = Platform {
899        button,
900        ble_radio,
901        pconsole,
902        console,
903        led,
904        gpio,
905        rng,
906        adc,
907        temp,
908        alarm,
909        analog_comparator,
910        ipc: kernel::ipc::IPC::new(
911            board_kernel,
912            kernel::ipc::DRIVER_NUM,
913            &memory_allocation_capability,
914        ),
915        i2c_master_slave,
916        spi_controller,
917        kv_driver,
918        scheduler,
919        systick: cortexm4::systick::SysTick::new_with_calibration(64000000),
920    };
921
922    base_peripherals.adc.calibrate();
923
924    debug!("Initialization complete. Entering main loop\r");
925    debug!("{}", &*addr_of!(nrf52840::ficr::FICR_INSTANCE));
926
927    (
928        board_kernel,
929        platform,
930        chip,
931        nrf52840_peripherals,
932        mux_alarm,
933    )
934}
935
936/// This is in a separate, inline(never) function so that its stack frame is
937/// removed when this function returns. Otherwise, the stack space used for
938/// these static_inits is wasted.
939#[inline(never)]
940pub unsafe fn start() -> (
941    &'static kernel::Kernel,
942    Platform,
943    &'static Chip,
944    &'static Nrf52840DefaultPeripherals<'static>,
945    &'static MuxAlarm<'static, nrf52840::rtc::Rtc<'static>>,
946) {
947    let (kernel, platform, chip, peripherals, mux_alarm) = start_no_pconsole();
948    let _ = platform.pconsole.start();
949    (kernel, platform, chip, peripherals, mux_alarm)
950}