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