NRF52840 Eval Kit

From Waveshare Wiki
Jump to: navigation, search
NRF52840 Eval Kit
Bluetooth 5.0 NRF52840 Eval Kit
NRF52840 Eval Kit

BLE5.0 Bluetooth 2.4G Wireless Module, NRF52840 Onboard
Core52840
Bluetooth 5.0 Core52840 NRF52840 Core Board
Core52840

BLE5.0 Bluetooth 2.4G Wireless Module, NRF52840 Onboard
{{{name3}}}

{{{name4}}}

{{{name5}}}

{{{name6}}}

1. Overview

As a kind of development kit based on Bluetooth 5.0, NRF52840 Eval Kit features onboard Raspberry Pi and Arduino compatible interface, supports Bluetooth 5.0. Compared with Bluetooth 4.0, its data communication speed is twice and up to 2Mbps, and the transmission distance is quadruple. It also supports Bluetooth MESH and 2.4 GHz protocol, which can control more devices and applications. Based on ARM Cortex-M4F structure, NRF52840 features 1MB Flash and 256kB RAM, and its running speed can reach to 64MHz, and it also can run small RTOS.

More

1.1 Overview of NRF52840 Eval Kit

NRF52840 Eval Kit.png
Interface Introduction
1. Arduino interface: for connecting Arduino shields
2. Raspberry Pi GPIO Interface: for connecting Expansion HAT for Raspberry Pi
3. USB TO UART Interface
4. USB interface: the USB port of nRF52840
5. 4 pin SWD debugging interface: Easy access to ARM Debugger for burning and simulation
6. 3. 3V or 5V power input/output interface: provides power output or powered from external power supply

Devices Introduction
7. Core52840: NRF52840 Core Module
8. CP2102: USB to serial port chip
9. Buzzer
10. RT9193-33: Level conversion chip
11. Optical sensors
12. Keys: Reset and user-defined buttons
13. LED Indicators: PWR: Power indicator
RXD/TXD: NRF52840 Serial Transceiver Indicator
LED1 ~ LED4: User-defined indicator
14. Power switch: Switch to USB: USB port power supply
Switch to Battery: CR2032 Battery Power
15. NFC Antenna Interface
16. TF card slot
17. CR2032 battery holder

Jumper/Solder Joint Description
18. Jumper caps
Short jumper: on-board peripherals are connected to the I/O specified by the sample program
Disconnect jumper: Custom I/O can be accessed using connector instead
19. Current test solder joints
0 ohm resistance is welded by default, and the current of the board can be tested after the 0 ohm resistance is disconnected

1.2 Overview of Core52840

  • Master Chip: nRF52840
  • Effective communication distance: 150m (open space), 40m (indoor space)
  • Transmission speed: 2Mbps, 1Mbps, 500kbps and 125kbps
  • Operating frequency band: 2.4 GHz
  • Operating voltage: 2.0 V ~ 3.6 V (recommended 3.0 V)
  • Operating temperature:-40 ℃ ~ + 85 ℃
  • Storage temperature:-55 ℃ ~ + 125 ℃
  • Product size: 18mm × 13.5 mm
  • Antenna interface: onboard antenna

1.3 Overview of nRF52840

  • Bluetooth 5.0, IEEE 802.15. 4-2006, 2.4 GHz Multiprotocol Transceiver
  • Compatible for NRF52, NRF51, NRF24L and NRF24AP Series
  • ARM Cortex-M4F 32-bit processor with FPU, 64MHz
  • 1MB of flash and 256kB of RAM
  • 48 GPIO ports
  • 2 two-wire interfaces (compatible for I2C)
  • 1 I2S digital audio interface
  • 12-bit 200KSPS ADC
  • 1 USB 2.0 interface
  • 1 QSPI serial port (32Mbps)
  • 4 SPI main interfaces, 3 SPI slave interfaces
  • 2 UART interfaces
  • 4-channel PWM interface
  • 1 SWD interface
  • Operating voltage range (1.7 V ~ 5.5 V)

2. Development Environment Setup

This chapter mainly introduces how to set up a development environment and download the programs. After learning this chapter, you can quickly learn the basic use of NRF52840.
Generally, NRF52840 adopts nRFgo Studio to program HEX firmware, such as the HEX firmware of Bluetooth protocol stack. However, due to the compatibility of Jlink driver versions in nRFgo Studio, NRFgo Studio can't be used on some computers. Herein we use command line instead of nRFgo Studio when setting developing environment to avoid compatibility issues.

2.1 Installing Keil and Software Development Kit

Download Keil from the official website and install it. Note that Keil requires license,otherwise it only can be used to compile codes which is smaller than 256kB
After Keil is installed successfully, the corresponding pack needs to be installed, and the pack of NRF52840 has been saved to the package. Click NordicSemiconductor.nRF_DeviceFamilyPack. 8.17. 0 to install.

2.2 Installing SEGGER Embedded Studio for ARM 4.10 a

If you need to test the Bluetooth MESH demos, you need to install the development environment. You can skip this part. The installation package has been saved to the package, so you can install it directly without license.

2.3 Install Serial Driver

The circuit of USB to serial port is designed on the development board, and the USB to serial port chip used is CP2102, so you need to install the driver at first. If you has already installed it, skip this part.
The CP2102 driver has been saved to the package, according to the number of computer bits and the system to select the appropriate driver.

  • Double-click the driver installer "CP210xVCPInstaller_xxx" to run it
  • Clicks next to finish installing

After the driver is installed successfully, connect the USB to the USB serial interface between the computer and the development board, enter computer-> management-> device manager, and click "port (COM and LPT)" to see the new port number of the serial port, which indicates that the serial port driver is successfully installed.

2.4 Install Jlink driver

JLink programmer is used to programming NRF52840, which needs to install Jlink driver. It will also be recognized by nRF5x-Command-Line-Tools for erasing NRF52840Flash, downloading Bluetooth protocol stack and so on, It is recommended to install drivers above V6.22. If the version is too low, it will not be recognized.
The Jlink driver has been saved to the package and you can double-click to install, but note that during installation, the Jlink driver may has been installed after installing Keil, so remember to check it in the installation interface. If you have installed Keil before JLink driver, don’t forget to check the option to cover it as below:
Jlinkdriver.png

2.5 Install nRFx-Command-Line-Tools

The installation package has been saved to resources, you can double-click to install it. When the installation is finished, open console, inpput nrfjprog-v to check. It should be as below if you install the tool successfully.
Linetool.png

2.6 Install APP

After finishing the above steps, if you need to debug Bluetooth on the mobile phone, you also need to install:
nRF Connect: Common debugging tool of mobile phone. It has no graphical interface for each experiment. What the user observes is the original data, and nRF Connect can display the RSSI curve, supports multiple slave devices. It has high compatibility and is commonly used in debugging.
nRF Toolbox: A tool for debugging BLE on the mobile phone. NRF Toolbox is used for some experiments, which has GUI such as heart rate meter, temperature meter and so on. It can directly display the specific heart rate curve, temperature curve. However, its only support some experiments at present, and is not very stable, and sometimes the service cannot be successfully connected.

2.7 Demo program download for bare metal peripherals

After setting up the development environment, you can try with some demo. The latest official version of SDK is adopted in this tutorial (SDK Version 15.2), which supports Bluetooth 5.0.
SDK package contains a large number of demos, which are divided into bare-metal programs without Bluetooth stack and bare-metal programs with Bluetooth stack procedures, its programming and downloading methods are different, the specific differences are as follows:
Bare-metal programs that do not run the Bluetooth protocol stack: usually refers to programs that do not use Bluetooth communication, but only use on-chip peripheral with Bluetooth, the path of this demo stored in SDK is:
NRF5_SDK_15.2.0_9412b96\ examples\ peripheral\
Under the SDK path, there are the following demos, including common on-chip peripherial demos, as shown in the following figure:
Deprogram.png

Take the flowing water lamp as an example to learn the use of on-chip peripherals in the official demo: Click blinky-> pca10056-> blank-> arm5_no_packs-> blink_pca10056. uvoptx, Open the project file with Keil, and you can open the running water lamp demo. In the demo, click to compile
Keil1.png
Under normal circumstances, compile 0 error, 0 warning. After compiling, click the magic wand on the right to enter the configuration interface:
Keil2.png

Click the Debug tab, click Settings, and select J-Link/J-TRACE Cortex to download the debug option Item, as shown in the following figure:
Jtrace.png


Click Settings, click the Debug tab, and select SW in the Port bar:
Sw.png
After that, click the Flash Download tab and check the following options:
Flashdown.png

After checking, click OK to complete the configuration.
When the configuration is finished, ARM Debugger (Jlink) is used to connect PC and NRF52840 Eval Kit.
After that, click Download to download the bare metal program to NRF52840. As shown in the following figure:
Load09.png
After downloading, you can see that the four LED lights of NRF52840 Eval Kit light up cyclically.
Note: LED3 is not compatible with the official SDK, so you need to connect L3 to P1.05 with the dupont wire, as shown in the following figure:
P1.05.png

2.8 Download Demo with Bluetooth Protocol Stack

Different from bare-metal programs, if you need to download programs with Bluetooth protocol stack, you should download Bluetooth protocol stack first. The following will take Bluetooth pass-through mode as an example to demonstrate how to download a demo with Bluetooth protocol stack. Specific operations are as follows:

  • First, you need to erase the on-chip Flash.The method of erasing is as follows: open the Window console, connect the nRF52840 to the PC with the ARM Debugger(Jlink), after connecting enter the following command:

Bp01.png
After erasing Flash, download the Bluetooth protocol stack. Generally, the Bluetooth protocol stack can only be downloaded after erasing Flash on the chip. The download method is as follows. Click to enter: NRF5_SDK_15.2.0_9412b96-> examples-> ble_periodic-> ble_app_uart-> pca1 0056-> s140-> arm5_no_packs-> ble_app_uart_pca10056_s140. uvprojx, after opening the demo of serialnet mode demo, choose flash_s140_nrf52_6.1.0_softdevice:
Flashs140.png
Then click to download the Bluetooth protocol stack.

  • Then, download the application and choose the nrf52840_xxaa:

Xxaa.png
After that, the download step is the same as the bare metal.

2.9 Supplementary Notes for Downloading

The officially recommended downloader is Jlink, and the experiment also adopts Jlink downloader. However, the experiment shows that if it is not the downloader of genuine J-link V9.0 and above, it will fail to download or erase, as shown in the following figure:
Note01.png
Cortex.png
Note2.png
Jlink also cannot read the chip, as shown in the following figure:
20160605.png
In this case, we can try to use ST-Link and E-Link to download. The author can read the chip and download it successfully by using ST-Link and E-Link when J-Link can't read the chip.
However, when using ST-Link and E-Link for downloading, only Keil can be used for downloading. If ST-Link Utility is used, the chip will not be read. The following will explain how to use Keil combined with ST-Link to erase Flash, download Bluetooth stack, Bluetooth application, bare metal program, download MESH program, etc.
Note: The programming algorithm for downloading Bluetooth protocol stack and the programming algorithm for downloading Bluetooth application program (or bare metal program) is different.
When downloading Bluetooth protocol stack, the programming algorithm must be selected as nRF52xxx_UICR and NRF52xx_SoftDevice Erase, if nRF52xxx_UICR and nRF52xx are selected, Flash cannot be completely erased.
Erase.png
When downloading applications and bare metal programs, the programming algorithms must be selected as nRF52xxx_UICR and nRF52xx.
00h.png

  • Keil combined with ST-Link to completely erase Flash:

-First: Select the drop-down option box as:
210.png
-Next: Click Flash-> Erase to completely erase Flash:
Erase03.png

  • Keil downloads bare-metal programs with ST-Link:

-First, ensure that the chip does not download the Bluetooth protocol stack. If the Bluetooth protocol stack is downloaded, it needs full erasing: Please refer to Keil combined with ST-Link complete erase for the process of complete erase Flash steps. If the Bluetooth protocol stack is not downloaded, skip this step.
-Next: Open the bare Keil project file, select ST-Link downloader, and select SWD downloader
Stlink.png
Stlink2.png
-Then: Click load to download 

  • Keil and ST-Link download the program with Bluetooth stack:

-First of all: To be on the safe side, you need to erase Flash completely. Please refer to the previous section for erasing process.
-Next: select ST-Link download mode and select the following drop-down box
Flashs14.png
Click load to download the Bluetooth protocol stack:
F8.png
-Then: select the Bluetooth application drop-down box:
Uart.png
-Finally: Click load to download the Bluetooth application:
Uartapp.png

  • Keil and ST-Link download the MESH program:

-First of all: because the official development environment of Bluetooth MESH does not adopt Keil, and the official development environment of Bluetooth MESH SEGGER Embedded Studio for ARM 4.10 a only supports Jlink download, it is necessary to compile and obtain the hex file of Bluetooth MESH by SEGGER Embedded Studio for ARM first.
Hex3.png

-Next: Open an NRF52840 bare metal Keil project and check the storage path of Objects files path, place the compiled hex file in the Objects folder of the project folder:
Hex5.png
-Then: name the Name of Executable as the name of the hex file, noting that the name must be followed by the hex suffix:
Hex4.png
-Finally: select ST-Link download method and click load to download Bluetooth MESH program:
Hex6.png

3. Setting up Bare-metal Project

Generally, developing NRF52840 requires SDK whose package has been stored in resources. SDK usually refers to peripheral SDK with Bluetooth protocol stack, and there is customized SDK for Zigbee, Thread and Mesh. Next, peripheral SDK with Bluetooth protocol stack will be adopted to explain how to configure in bare metal engineering. Herein we adopts SDK V15.2, and creating new projects can also refer to keil project under the following path of SDK decompression package: NRF5_SDK_15.2.0_9412b96\ examples\ ble_periodic\ ble_app_template\ pca1 0056\ s140\ arm5_no_packs\ ble_app_template_pca10056_s140. uvprojx

3.1 Introduction to SDK Package

The folders under the SDK package are introduced before you create a new project to help you understand later:
PicB.png
Note, herein we adopt MDK5 development environment, and you can directly open project files with MDK5 without installing documents required to install MDK4 project.
The main folders under the SDK folder are described below:

  • Components: Contains all kinds of functions needed for development, such as bare metal, BLE, or 2.4 G programs, all need to use the files under the Components file, and the directory of Components is shown in the following figure:

PicA.png

  • Examples: This folder holds all the demos in the SDK, including the BLE master, the BLE slave, BLE master-slave integrated machine, chip peripherals and other demos.

 Because each example in the file contains multiple development environment projects and multiple chip projects, the using time needs to be distinguished. Take the demo of "Bluetooth Heart Rate Meter" as an example to illustrate how to open the project of nRF52840 in MDK5 development environment.
The path for the demo of Bluetooth Heart Rate Meter in SDK is:
NRF5_SDK_15.2.0_9412b96\ examples\ ble_peripheral\ ble_app_hrs\ pca10056\ S140\ arm5_no_packs\ ble_app_hrs_pca10056_s140.uvprojx Some of these paths mean:
PCA10056: The name of the development board corresponding to NRF52840 in the official development board is PCA10056.
S140: This time, the latest Bluetooth protocol stack is adopted, and S140 protocol stack is used.
Arm5_no_packs: The MDK5 development environment is used this time, and the Arm5_no_packs item needs to be opened.

  • Integration and modules: Integration stores an "older version" of the chip peripheral drive

Moving program, modules is stored in the new version of peripheral drivers. Before SDK15.0, the peripheral driver of the chip existed in the Component folder Drivers_nrf directory. Beginning with SDK 15.0, Nordic began to rewrite the peripheral driver and Named "nrfx", the new version of peripheral driver is saved in the modules directory; And the outside driver program of the old version is saved in the Integration directory, and the name is changed to "nrfx". The "old version" of the chip peripheral driver and the "new version" of the chip peripheral driver can be integrated at the same time.

3.2 New Project Template

The project catalog are as follows:
First, there are the following folders under the project directory:
3.2.png
In the project directory, there are DRIVER, SDK, TEMP and USER folders.

  • The DRIVER folder:The folder mainly saves hardware peripheral drivers, such as MPU6050 and other peripheral driver files external to the development board, which belong to the files created by the user.
  • SDK folder: mainly selects some files from the official SDK, and the selected folders are as follows:

3.2.2.png
These are the files selected under the SDK folder. In fact, you only need to use these files in the official SDK. Components includes all kinds of functions needed for development, and external contains all kinds of functions. Third-party functions, such as freertos functions, integration contains older versions of peripheral drivers, Modules contains the new version of the peripheral driver.

  • TEMP: an intermediate file in the compilation process, and files under this folder can be deleted.
  • USER: user files

Userfile.png
Generally, files in folders SDK, DRIVER and TEMP are same for different project. What the difference is the files of APPLICATION, IDE and so on, that is, what USER files store are different folders and files from different projects by users. This design can save memory, on the other hand, when users want to create their own projects inn a certain demo, they can easily finish it.
The above is the main structure of the new project template.

3.3 New Project

You can create new projects before setting folders for the project and copying functions.
Please search how Keil create the project online. The following mainly explains the main precautions in the process of creating the project: First, the peripheral driver file for users is placed under the DRIVER folder, as shown in the following figure:
Project.png
Second, the new project created by the user should be placed under the USER path, and attention should be paid to naming, as shown in the following figure:
Project2.png
Third, the user application functions should be placed under the path: USER/User Project Folder/APPLICATION Folder:
Project3.png
Fourth, try to put the keil project files under the IDE folder:
Project4.png
Fifth, place the obj file in the TEMP folder as much as possible:
Project5.png
Sixth, the established engineering documents should meet the following structure as far as possible, and keep consistent with the official engineering document folder structure.
Sixth.png
Seventh, pay attention to the device package version, and try to keep the selected device package version consistent with the device package version in the official examples project, as shown in the following figure:
Seventh2.png
For more details, please refer to the setup details of keil project in the official demo

4. GPIO Output Drives LED

This chapter will explain how to operate the GPIO of NRF52840, amd how to configure GPIO in the library function, and set GPIO bit, clear and apply reverse function, and on this basis, further introduce the preparation of running water lamp program.
The demos you need to use in this chapter are: 001_LED

4.1 Software Design

4.1.1 Introduction to GPIO

The GPIO of NRF52840 has the following features:
• Up to 32 GPIO pins per GPIO port
• Configurable output drive strength
• Built-in pull-up and pull-down resistors
• A high or low level of any GPIO can trigger wake-up
• Arbitrary GPIO can trigger jump edge interrupt
• PPI task/event system can use any GPIO port
• You can control one or more GPIO outputs through PPI and GPIOTE channels
• All pins can be mapped individually to peripheral interfaces for layout flexibility

4.1.2 Introduction to Library Function

The main library functions involved in GPIO operations are

nrf_gpio_cfg_output() //set GPIO as output
nrf_gpio_pin_set() //Drive the specified GPIO output high
nrf_gpio_pin_clear() //Drive the specified GPIO output low
nrf_gpio_pin_toggle() //Reverses the output state of the specified GPIO
NRF_GPIO_PIN_MAP() //Map port and pin numbers to numeric values

NEF_GPIO_PIN_MAP () maps port and pin numbers to numeric values means P0.0 to P0.31 is mapped to 0 to 31, and P1.0 to P1.15 is mapped to 32 to 47.

4.1.3 Running Water Lamp Experiment

The following code will be written, and the provided demos corresponding to the code here are: 001_LED.
First, check the led.h file, as shown below, the main macro defines the macro that the LED pin number maps to the numerical value, and the LED_On(), LED_Off() functions, as shown below:

#ifndef __LED_H__
#define __LED_H__
#include "nrf.h"
#include "nrf_gpio.h"
#define LED0 NRF_GPIO_PIN_MAP(0,13)
#define LED1 NRF_GPIO_PIN_MAP(0,14)
#define LED2 NRF_GPIO_PIN_MAP(0,19)
#define LED3 NRF_GPIO_PIN_MAP(0,16)
void LED_On(uint32_t led_number);
void LED_Off(uint32_t led_number);
#endif

Next, check the led. c file, as shown below, mainly implementing the LED_On () function and LED_Off () function:
Finally, look at the main.c file, as shown below, and keep the four LEDs on for 500ms and off for 500ms, LED control is now available.

#include "led.h"
void LED_On(uint32_t led_number)
{
nrf_gpio_cfg_output(led_number);
nrf_gpio_pin_clear(led_number);
}
void LED_Off(uint32_t led_number)
{
nrf_gpio_cfg_output(led_number);
nrf_gpio_pin_set(led_number);
}

Finally, look at the main.c file, as shown below, and keep the four LEDs on for 500ms and off for 500ms, LED control is now available.

int main(void)
{
while (true)
{
LED_On(LED0);
LED_On(LED1);
LED_On(LED2);
LED_On(LED3);
nrf_delay_ms(500);

LED_Off(LED0);
LED_Off(LED1);
LED_Off(LED2);
LED_Off(LED3);
nrf_delay_ms(500);
 }
}

4.2 Hardware Design

NRF52840 Eval Kit has 4 LEDs on board: LED1, LED2, LED3, LED4, and 4 LEDs respectively access to P0.13, P0.14, P0.19, P0.16, as shown in the following table:

UART GPIO
LED1 P0.13
LED2 P0.14
LED3 P0.19
LED4 P0.16

Among them, LED3 in the official SDK is connected to P0.15, which is incompatible with the official demo. If you want to use the official SDK and LED3, you need to change the pin of LED3 in SDK to P1.09, The rest of the LEDs are compatible with the official SDK. The LED part of the schematic diagram of the development board is shown in the following figure:
Userled.png
Among them, Header 4X2 is the jumper connecting NRF52840 with LED, which is connected with jumper caps (L1, L2, L3, L4 jumper caps) are connected with the cathode of LED and GPIO port of processor.
Compiled and downloaded. After downloading successfully, it can be observed that the 4 LEDs are on for 500ms and off for 500ms continuously.

5. Serial Port Sending and Receiving

This chapter will introduce the serial port transceiver function of NRF52840, the operation of NRF52840 serial port sending and receiving data, NRF52840 can send data to serial port debugging assistant, and when serial port debugging assistant sends corresponding data to NRF52840, the corresponding LED on NRF52840 Eval Kit will be correspondingly on or off. 
The demo used in this chapter is: 003_UART

5.1 Software Design

5.1.1 Introduction to the SDK

First of all, the structure of NRF52840 serial port is shown in the following figure:
Sdk1.png
The serial port supports full-duplex communication, supports automatic hardware flow control, supports parity check and the generation of the 9th data bit. The serial port sends and receives data directly through TXD and RXD registers, and adopts 1-bit stop bit.
In NRF52840, the pins related to the serial port: RXD, CTS, RTS, TXD, etc. are mapped by configuring the registers PSEL.RXD, PSEL.CTS, PSEL.RTS, PSEL.TXD respectively.

5.1.2 Introduction to Library Function

In the library function, a macro for serial port initialization is defined at first: APP_UART_FIFO_INIT,
The macro definition expands as follows:

#define APP_UART_FIFO_INIT(P_COMM_PARAMS, RX_BUF_SIZE, TX_BUF_SIZE, 
EVT_HANDLER, IRQ_PRIO, ERR_CODE) \
do \
{ \
app_uart_buffers_t buffers; \
static uint8_t rx_buf[RX_BUF_SIZE]; \
static uint8_t tx_buf[TX_BUF_SIZE]; \
\
buffers.rx_buf = rx_buf; \
buffers.rx_buf_size = sizeof (rx_buf); \
buffers.tx_buf = tx_buf; \
buffers.tx_buf_size = sizeof (tx_buf); \
ERR_CODE = app_uart_init(P_COMM_PARAMS, &buffers, EVT_HANDLER, 
IRQ_PRIO); \
} while (0)

In this macro definition, APP_UART_FIFO_INIT encapsulates the app_uart_init () function, and it also defines the serial port receive and send buffer, the size of serial port receive and send buffer, etc.
In this macro definition, app_uart_buffers_t constructs the variable buffers, which is used to hold data sent and received.

The app_uart_buffers_t structure is declared as follows:
/**@brief UART buffer for transmitting/receiving data.
*/
typedef struct
{
uint8_t * rx_buf; /**< Pointer to the RX buffer.*/
uint32_t rx_buf_size; /**< Size of the RX buffer. */
uint8_t * tx_buf; /**< Pointer to the TX buffer.*
uint32_t tx_buf_size; /**< Size of the TX buffer.*/
} app_uart_buffers_t;

The APP_UART_FIFO_INIT macro, a macro with parameters, has 5 input parameters and 1 output parameter. The application needs the corresponding input parameters when calling the macro, and at the same time, the application can use the output parameters to get the result of macro execution, that is, the error code.
The first input parameter, P_COMM_PARAS: the communication parameter configuration structure pointing to the serial port, app_uart_comm_params_t structure is declared as follows:

/**@brief UART communication structure holding configuration settings
for the peripheral.
*/
typedef struct
{
uint32_t rx_pin_no; /**< RX pin number. */
uint32_t tx_pin_no; /**< TX pin number. */
uint32_t rts_pin_no; /**< RTS pin number, only used
if flow control is enabled. */
uint32_t cts_pin_no; /**< CTS pin number, only used
if flow control is enabled. */
app_uart_flow_control_t flow_control; /**< Flow control setting,
if flow control is used, the system will use low power UART mode, 
based on CTS signal. */
bool use_parity; /**< Even parity if TRUE, no
parity if FALSE. */
uint32_t baud_rate; /**< Baud rate configuration.
*/
} app_uart_comm_params_t;

The second input parameter: RX_BUF_SIZE: receive cache size.
The third input parameter: TX_BUF_SIZE: Send cache size.
The fourth input parameter: EVT_HANDLE: serial port time handle.
The fifth input parameter: IRQ_PRIO: interrupt priority.

Output parameter ERR_CODE: Error code used to feed back the result of serial port initialization to the application.
The above is the introduction of the serial initialization macro APP_UART_FIFO_INIT. After finishing the serial initialization, the serial interrupt handling function is introduced. There are the following types of serial interrupts, as follows:

typedef enum
{
APP_UART_DATA_READY,
APP_UART_FIFO_ERROR,
APP_UART_COMMUNICATION_ERROR,
APP_UART_TX_EMPTY,
APP_UART_DATA,
} app_uart_evt_type_t;

Serial interrupt processing function should follow the corresponding format, and the format of this serial interrupt processing function
As follows:

void uart_error_handle(app_uart_evt_t * p_event)
{
if (p_event->evt_type == APP_UART_COMMUNICATION_ERROR)
{
APP_ERROR_HANDLER(p_event->data.error_communication);
}
else if (p_event->evt_type == APP_UART_FIFO_ERROR)
{
APP_ERROR_HANDLER(p_event->data.error_code);
 }
}

These are the main precautions for serial port initialization and serial port interrupt function.

5.1.3 Serial Port Lighting and Echo

Main.c, uart.c, uart.h and other corresponding files in the serial port definition, implementation, call, etc.
uart.h:

#ifndef _UART_H_
#define _UART_H_
#include "nrf.h"
#include "nrf_gpio.h"
#include "app_uart.h"
#include "nrf_uart.h"
#define RX_PIN_NUMBER NRF_GPIO_PIN_MAP(0,8)
#define TX_PIN_NUMBER NRF_GPIO_PIN_MAP(0,6)
#define CTS_PIN_NUMBER NRF_GPIO_PIN_MAP(0,7)
#define RTS_PIN_NUMBER NRF_GPIO_PIN_MAP(0,5)
#define UART_HWFC APP_UART_FLOW_CONTROL_DISABLED
#define MAX_TEST_DATA_BYTES (15U)
#define UART_TX_BUF_SIZE 256
#define UART_RX_BUF_SIZE 256
extern app_uart_comm_params_t comm_params;
void uart_error_handle(app_uart_evt_t * p_event);
#endif

uart.c:

#include "uart.h"
app_uart_comm_params_t comm_params =
{
RX_PIN_NUMBER,
TX_PIN_NUMBER,
RTS_PIN_NUMBER,
CTS_PIN_NUMBER,
UART_HWFC,
false,
NRF_UART_BAUDRATE_115200
};
void uart_error_handle(app_uart_evt_t * p_event)
{
if (p_event->evt_type == APP_UART_COMMUNICATION_ERROR)
{
APP_ERROR_HANDLER(p_event->data.error_communication);
}
else if (p_event->evt_type == APP_UART_FIFO_ERROR)
{
APP_ERROR_HANDLER(p_event->data.error_code);
 }
}

main.c:

#include "nrf.h"
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include "app_uart.h"
#include "app_error.h"
#include "nrf_delay.h"
#include "nrf_uart.h"
#include "nrf_uarte.h"
#include "led.h"
#include "uart.h"
/**
* @brief Function for main application entry.
*/
int main(void)
{
uint32_t err_code;

APP_UART_FIFO_INIT(&comm_params,UART_RX_BUF_SIZE,UART_TX_BUF_SIZE
,uart_error_handle,APP_IRQ_PRIORITY_LOWEST,err_code);

APP_ERROR_CHECK(err_code);
printf("\r\nUART example started.\r\n");
while (true)
{ 
uint8_t cr;
//Get Data from the port!
while (app_uart_get(&cr) != NRF_SUCCESS);
//Then put data to the port
while (app_uart_put(cr) != NRF_SUCCESS);
switch (cr)
{
case '1':
{
printf("\r\n LED0 ON \r\n");
LED_On(LED0);
break;
}
case '2':
{
printf("\r\n LED0 OFF \r\n");
LED_Off(LED0);
break;
}
case '3':
{
printf("\r\n LED1 ON \r\n");
LED_On(LED1);
break; 
}
case '4':
{
printf("\r\n LED1 OFF \r\n");
LED_Off(LED1);
break;
}
case '5':
{
printf("\r\n LED2 ON \r\n");
LED_On(LED2);
break; 
}
case '6':
{
printf("\r\n LED2 OFF \r\n");
LED_Off(LED2);
break;
}
case '7':
{
printf("\r\n LED3 ON \r\n");
LED_On(LED3);
break; 
}
case '8':
{
printf("\r\n LED3 OFF \r\n");
LED_Off(LED3);
break;
}
case 'q':
{
printf("\r\n Exit! \r\n");
while (true);
}
case 'Q':
{
printf("\r\n Exit! \r\n");
while (true); 
}
default:
{
printf("\r\nPlease input correct command\r\n");
break;
   }
  }
 }
} 

Among them, in the main function, the redirection to the serial port is adopted, and data can be sent to the serial port through the printf function. When the program starts, it will send " \r\nUART example started.\r\n"; in the main loop, when the serial port receives the corresponding data, it will send the corresponding LED on and off prompts, and change the corresponding status of LED.
The specific operations are as follows: when 1 is received, the LED1 turn on, and when 2 is received, the LED1 turn off; When receiving 3, LED2 is turned on, when 4 is received, LED2 is turned off, and so on.

5.2 Hardware Design

In the hardware schematic diagram of NRF52840 Eval Kit, the serial port part is designed as follows:
Hardware1.png
Among them, H1 and H2 are the jumper cap of the serial port. Only when H1 and H2 are connected to jumper caps (connect jumper caps TX and RX, if hardware flow control is required, jumper cap CTS and RTS needs to be connected.), the USB-to-serial interface is connected to the NRF52840 chip.
The advantage of USB-to-serial chip is that you can use a USB cable to connect the computer to USB without USB-to-serial tools. If you have installed the driver according to step 2.2, open the device manager to view corresponding serial port number.
In this design, the relevant pins are defined as follows:

UART GPIO
CPTX P0.06
CPRX P0.08
CPRTS P0.25
CPRTS P0.07

Among them, the pin defined by CPRTS in the official SDK is P0.05, but in NRF52840 Eval Kit,the pin defined by CPRTS is P0.25. If you need to use the SDK of NRF52840 Eval Kit and the Hardware control flow for the serial port, you need to change the CPRTS pin definition to P0.25.
Compile and download the program. After the download is completed, connect the USB cable to the USB TO UART port of the NRF52840 Eval Kit and the USB port of PC, open serial debugging assistant, choose the corresponding com port, you can observe the data sent by NRF52840 through serial port. At the same time, you could send 1 or 2 to NRF52840 through serial port respectively, LED1 would turn on or off accordingly, as shown in the following figure:
Xcom.png

6. SPI

This chapter will introduce the application of SPI interface of NRF52840. First, we will introduce a test example of SPI: connect the MISO of SPI interface to MOSI, and carry out loop-back test. Then, we will introduce how NRF52840 driver a 0.96 inch OLED and the precautions. The demos to be used in this chapter are: 004_SPI (Example), 005_SPI (OLED)

6.1 Software Design

6.1.1 Introduction to SPI

Pins corresponding to SPI interface of NRF52840 can be freely allocated, and SPI main controller provides simple CPU interface, including TXD register for sending data and RXD register for receiving data.
The host architecture of the SPI for the NRF52840 is shown below:
Spix.png

Among them, RXD-1 and TXD+1 illustrate the double buffered versions of TXD and RXD respectively.
For SPI communication, data has transmission timing, namely clock phase (CPHA) and clock polarity (CPOL) combination:
The level of CPHA determines whether the serial synchronization clock is to be collected at the first clock transition edge or the second clock transition edge. When CPHA=0, the data is collected at the first transition edge.
The level of CPOL determines the idle state level of the serial synchronous clock, CPOL=0 means low, CPOL=1 means high.
The operating modes in SPI 4 correspond to the following figure:
Spi4.png
In NRF52840, SPI_MODE0 is adopted by default.

6.1.2 Introduction to Library Function

Several library functions commonly used in SPI communication:
The first is the library function: nrf_drv_spi_init ()

ret_code_t nrf_drv_spi_init(nrf_drv_spi_t const * const p_instance,
                            nrf_drv_spi_config_t const * p_config,
                            nrf_drv_spi_evt_handler_t handler,
                            void * p_context);

In this library function, there are several parameters, which are:

*//@param[in] p_instance Pointer to the driver instance structure.

This parameter is used to determine which SPI is used, and NRF52840 can allocate 4 SPIs for peripheral use.

//@param[in] p_config Pointer to the structure with the initial
configuration.
This parameter is a structure variable, which is used to pass in the initialized parameter.
//@param handler Event handler provided by the user. If NULL, transfers

This parameter is the interrupt callback function. When the transmission is completed or the reception is completed, it will enter the function. If the function parameter is set to NULL during initialization, it will not enter the interrupt callback function.

*//@param p_context Context passed to event handler.

This function is the parameter passed to the interrupt callback function.

NRF_SUCCESS //Succeed Initialization
NRF_ERROR_INVALID_STATE //Already initialized
NRF_ERROR_BUSY //SPI classes may instantiated with the same ID

The above parameters are the possible results returned by this function.

  • Next is the library function: nrf_drv_spi_transfer()
__STATIC_INLINE
ret_code_t nrf_drv_spi_transfer(nrf_drv_spi_t const * const
p_instance,
             uint8_t const * p_tx_buffer,
             uint8_t tx_buffer_length,
             uint8_t * p_rx_buffer,
             uint8_t rx_buffer_length);

In this library function, there are several parameters, namely:

*//@param[in] p_instance Pointer to the driver instance structure.

This parameter is an instantiation object of the SPI

*//@param[in] p_tx_buffer Pointer to the transmit buffer. Can be NULL
//if there is nothing to send.

This parameter is the send buffer of the SPI

*//@param tx_buffer_length Length of the transmit buffer.

This parameter is the length of the SPI send buffer:

*//@param[in] p_rx_buffer Pointer to the receive buffer. Can be NULL
//if there is nothing to receive.

This parameter is the SPI receive buffer:

*//@param rx_buffer_length Length of the receive buffer.

This parameter is the length of the SPI receive buffer.
This function is used when starting sending and receiving SPI data.
Next, we will experience the use of SPI interface of NRF52840 through two SPI application demos: In both demos, the spi.h file is identical to the spi.c file, as follows:
spi.h:

#ifndef _SPI_H_
#define _SPI_H_
#include "nrf.h"
#include "nrf_gpio.h"
#include "nrf_drv_spi.h"
#include "nrf_log.h"
#define SPI_INSTANCE 0
#define TEST_STRING "Nordic"
#define CS_PIN NRF_GPIO_PIN_MAP(1,12)
#define MOSI_PIN NRF_GPIO_PIN_MAP(1,13)
#define MISO_PIN NRF_GPIO_PIN_MAP(1,14)
#define SCK_PIN NRF_GPIO_PIN_MAP(1,15)
extern nrf_drv_spi_t spi;
extern volatile bool spi_xfer_done;
extern uint8_t m_tx_buf[];
extern uint8_t m_rx_buf[sizeof(TEST_STRING) + 1];
extern uint8_t m_length;
void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
void * p_context);
void spi_write(const void * data, size_t size);
#endif

spi.c:

#include "spi.h"
#include "ssd1306.h"
nrf_drv_spi_t spi = NRF_DRV_SPI_INSTANCE(SPI_INSTANCE);
volatile bool spi_xfer_done;
uint8_t m_tx_buf[] = TEST_STRING;
uint8_t m_rx_buf[sizeof(TEST_STRING) + 1];
uint8_t m_length = sizeof(m_tx_buf);
/**
* @brief SPI user event handler.
* @param event
*/
void spi_event_handler(nrf_drv_spi_evt_t const * p_event,
void * p_context)
{
 spi_xfer_done = true;
 NRF_LOG_INFO("Transfer completed.");
 if (m_rx_buf[0] != 0)
 {
   NRF_LOG_INFO(" Received:");
   NRF_LOG_HEXDUMP_INFO(m_rx_buf, strlen((const char
*)m_rx_buf));
}
}
void spi_write(const void * data, size_t size)
{
  APP_ERROR_CHECK(nrf_drv_spi_transfer(&spi, data, size, NULL, 0));
}

6.1.3 SPI Loop-back Test

In the SPI loop demo, the content in main.c is:

#include "nrf_drv_spi.h"
#include "nrf_gpio.h"
#include "app_util_platform.h"
#include "nrf_delay.h"
#include "app_error.h"
#include <string.h>
#include "nrf_log.h"
#include "nrf_log_ctrl.h"
#include "nrf_log_default_backends.h"
#include "spi.h"
int main(void)
{
 APP_ERROR_CHECK(NRF_LOG_INIT(NULL));
 NRF_LOG_DEFAULT_BACKENDS_INIT();
 nrf_drv_spi_config_t spi_config = NRF_DRV_SPI_DEFAULT_CONFIG;
 spi_config.ss_pin = CS_PIN;
 spi_config.miso_pin = MISO_PIN;
 spi_config.mosi_pin = MOSI_PIN;
 spi_config.sck_pin = SCK_PIN;
 /*
 Doesn't print what to send or what received in SPI
 */
 //APP_ERROR_CHECK(nrf_drv_spi_init(&spi, &spi_config, NULL,
 NULL));
 /*
 Print what to send or what received in SPI
 */
 APP_ERROR_CHECK(nrf_drv_spi_init(&spi, &spi_config,
spi_event_handler, NULL));
 NRF_LOG_INFO("SPI example started.");
 NRF_LOG_FLUSH();
 while (1)
 {
 memset(m_rx_buf, 0, m_length);
 spi_xfer_done = false;
 APP_ERROR_CHECK(nrf_drv_spi_transfer(&spi, m_tx_buf, m_length,
m_rx_buf, m_length));
while (!spi_xfer_done)
{
__WFE();
}
NRF_LOG_FLUSH();
nrf_delay_ms(500);
 }
}

6.1.4 SPI-driven OLED

In the SPI-driven OLED demo, it mainly explains the precautions for SPI-driven OLED, and explains the implementation of its underlying driver.
Precautions:
1. In the process of NRF52840 using SPI to drive OLED, when initializing SPI, try not to add an interrupt callback function, as follows:

/*
Doesn't print what to send or what received in SPI
*/
//APP_ERROR_CHECK(nrf_drv_spi_init(&spi, &spi_config, NULL, NULL));
/*
Print what to send or what received in SPI
*/
APP_ERROR_CHECK(nrf_drv_spi_init(&spi, &spi_config, spi_event_handler, NULL));

2. If there is an interrupt callback function, you must add an appropriate amount of delay to the SPI read and write, as follows:

void Single_Command(unsigned char cmd)
{
nrf_gpio_pin_clear(DC);
//if SPI is busy Frequently,delay here 
nrf_delay_us(30);
spi_write(&cmd, sizeof(cmd));
}

Among the underlying driving functions of OLED, the most important things are command writing function and data writing function , as follows:
Command writing function:

void Single_Command(unsigned char cmd)
{
nrf_gpio_pin_clear(DC);
//if SPI is busy Frequently,delay here
//nrf_delay_us(30); 
spi_write(&cmd, sizeof(cmd));
}

Data writing function:

void Single_Data(unsigned char dt)
{
nrf_gpio_pin_set(DC);
//if SPI is busy Frequently,delay here
//nrf_delay_us(30); 
spi_write(&dt, sizeof(dt));
}

In command writing function and data writing function, the Spi_write() function is defined in spi.c.
The above are the key points of the program design of NRF52840 using SPI for loop-back testing and lighting OLED.

6.2 Hardware Design

In the design of SPI hardware, the SPI interface is mainly led out through Arduino interface, as shown in the following figure:
Cs.png
Moreover, in this design, the pin definition is different from that in the official SDK, which is mainly reflected in the inconsistency between the SPI pin defined in this demo and the official SDK. If you need to use the official SDK to apply it to NRF52840 Eval Kit, you need to modify the corresponding pin definition.
In this design, the relevant pins are defined as follows:
Ar.png

Compile and download the program. After downloading:
In the SPI loop-back test demo: the MISO port of the SPI will receive the data sent from the MOSI port. As shown in the following figure, the sender sends Nordic and the receiver also receives Nordic:
Oled.png
In the OLED test demo, the OLED will display the following image:
Oled2.png

7. I2C

This chapter will introduce the application of I2C interface of NRF52840. First, it will introduce the application of I2C detecting slaver address, that is, when a device is connected to I2C bus, the master device will scan the slaver address to ensure the normal I2C communication; Then NRF52840 drives BME280 through I2C interface to detect temperature, humidity, atmospheric pressure and other data, and prints them to serial debugging assistant for observation.
The demos to be used in this chapter are: 006_I2C (Scan Device), 007_I2C (BME280), 008_I2C (MPU6050 3D COUBE)

7.1 Software Design

7.1.1 Introduction to TWI

In NRF52840, there is a TWI interface (two wire interface), which can communicate with I2C devices. The pins corresponding to the TWI interface of NRF52840 can be freely allocated, and the TWI master device is compatible with the I2C interface (when the transmission rate is between 100kHz and 400kHz). The TWI internal structure design of NRF52840 is shown in the following figure:
Twi.png
TWI master device starts communication transmission by triggering STARTTX task and opening STARTRX task, and stops by triggering STOP task. If slaver device triggers NACK signal, ERROR event will occur in TWI master device.
Note that if there are other devices with the same ID as TWI, and you want to use TWI, you need to disable other devices first. Disabling devices with the same ID will not reset their registers. Therefore, to ensure correct operation, you need to disable devices with the same ID as TWI first.

7.1.2 Introduction to Library Function

Several library functions commonly used in I2C communication:
Library function: nrf_drv_twi_init ();

ret_code_t nrf_drv_twi_init(nrf_drv_twi_t const * p_instance,
                            nrf_drv_twi_config_t const * p_config,
                            nrf_drv_twi_evt_handler_t event_handler,
                            void * p_context);

In this library function, there are four parameters, which are:

//@ param [in] p_instance Pointer to the driver instance structure.

This parameter represents an object instantiated by an I2C class, because NRF52840 can allocate two I2C interfaces

//@ param [in] p_config initial configuration.

This parameter is a structure variable, which is used to pass in the initialized parameter.

//@ param [in] event_handler event handler provided by the user. If
//NULL, blocking mode is enabled.

This parameter is an interrupt callback function, which will enter the function when sending or receiving is finished. If the function parameter is set to NULL during initialization, it will not enter the interrupt callback function.

//@ param [in] p_context context passed to event handler.

This function is the parameter passed to the interrupt callback function.

NRF_SUCCESS//Initialized successfully
NRF_ERROR_INVALID_STATE//has already been initialized
NRF_ERROR_BUSY//It is possible that the SPI class instantiates the same ID

The above parameters are the possible results returned by this function.
Library function:

nrf_drv_twi_rx ();
__STATIC_INLINE
Ret_code_t nrf_drv_twi_rx (nrf_drv_twi_t const * p_instance,
                           Uint8_t address,
                           Uint8_t * p_data,
                           Uint8_t length)

The function is to receive the data from the slave and save it to the cache.
In this function, you have the following parameters:

//@ param [in] p_instance Pointer to the driver instance structure.

This parameter is an object instantiated by the I2C class, because NRF52840 can assign two I2C interfaces, which interface is determined by the instantiated object.

//@ param [in] address address of a specific slave device (only 7
//LSB).

This parameter is a 7-bit slave part address.

//@ param [in] p_data Pointer to a transfer buffer.

This parameter is a pointer to the cache of data to be sent.

//@ param [in] length Number of bytes to send.

This parameter is the length (bytes) of the data to be sent

//@ param [in] no_stop If set, the stop condition is not generated
//On the bus after the transfer has completed successfully (allowing
//for a repeated start in the next transfer).

This parameter is whether to generate stop bit. If it is set to 1, no stop bit will be generated, and the next transfer is allowed to be restarted Losing; If set to 0, a stop bit is generated.
Library function:

nrf_drv_twi_tx ();
__STATIC_INLINE
Ret_code_t nrf_drv_twi_rx (nrf_drv_twi_t const * p_instance,
                           Uint8_t address,
                           Uint8_t * p_data,
                           Uint8_t length);

The function is to send the data in the cache to the slave.
The argument to this function has the same meaning as the argument to the library function nrf_drv_twi_rx (). Functions:

Nrf_drv_twi_init ();
ret_code_t nrf_drv_twi_init (nrf_drv_twi_t const * p_instance,
                             nrf_drv_twi_config_t const * p_config,
                             nrf_drv_twi_evt_handler_t event_handler,
                             void * p_context);

The function is used to initialize I2C devices, which are initialized before they are used.
In this function, you have the following parameters:

//@ param [in] p_instance Pointer to the driver instance structure.

This parameter is an object instantiated by the I2C class, because NRF52840 can assign two I2C interfaces, which interface is determined by the instantiated object.

//@ param [in] p_config initial configuration.

This parameter defines the parameters for I2C initialization, such as SCL, SDA pin, I2C rate, I2C interrupt priority, and so on.

//@ param [in] event_handler event handler provided by the user. If
//NULL, blocking mode is enabled.

This parameter defines interrupt handling functions, such as interrupt when data is sent, interrupt after data is received, and so on.

//@ param [in] p_context context passed to event handler.

This parameter defines the parameters entered into the interrupt handler.
These are the common functions of I2C. Below, we will introduce I2C scanning slave devices, driving BME280, driving MPU6050 and other related demos.

7.1.3 I2C Scan Slave Device

I2C Scan Slave Device demo: If a device is connected to the I2C bus, its slave address will be scanned. The program for I2C scanning the address of the slave machine is:

for(address=1; address<=TWI_ADDRESSES; address++)
{
err_code = nrf_drv_twi_rx(&m_twi, address, &sample_data,
sizeof(sample_data));
if (err_code == NRF_SUCCESS)
{
 detected_device = true;
 device_address = address;
 NRF_LOG_INFO("TWI device detected at address 0x%x.", address);
 NRF_LOG_FLUSH();
 } 
}

The program mainly traverses slave parts address, if the I2C host can successfully received data from the traversal of a slave address, then determine that the slave address is valid, scan to the slave equipment, the slave equipment address will be printed out.

7.1.4 I2C Reads BME280 Data

I2C drives BME280 demo: BME280 is a trinity environmental sensor integrating temperature, humidity, air pressure and released by Bosch Company. This demo can realize the bottom interface of the official library by I2C driver and read data such as temperature, humidity and air pressure. BME280 officially provided by Bosch is among the official GitHub:
https://github.com/BoschSensortec/BME280_driver
According to the description, the sensor can be driven by I2C or SPI, and to drive the sensor, you only need to implement the corresponding I2C/SPI read-write function. The I2C/read-write function to be implemented is as follows (the following parts are from the README page of GitHub):

int8_t user_i2c_read(uint8_t dev_id, uint8_t reg_addr, uint8_t
*reg_data, uint16_t len)
{
int8_t rslt = 0; /* Return 0 for Success, non-zero for failure */
/*
* The parameter dev_id can be used as a variable to store the I2C 
address of the device
*/
/*
* Data on the bus should be like
* |------------+---------------------|
* | I2C action | Data |
* |------------+---------------------|
* | Start | - |
* | Write | (reg_addr) |
* | Stop | - |
* | Start | - |
* | Read | (reg_data[0]) |
* | Read | (....) |
* | Read | (reg_data[len - 1]) |
* | Stop | - |
* |------------+---------------------|
*/
return rslt;
}
int8_t user_i2c_write(uint8_t dev_id, uint8_t reg_addr, uint8_t
*reg_data, uint16_t len)
{
int8_t rslt = 0; /* Return 0 for Success, non-zero for failure */
/*
* The parameter dev_id can be used as a variable to store the I2C 
address of the device
*/
/*
* Data on the bus should be like
* |------------+---------------------|
* | I2C action | Data |
* |------------+---------------------|
* | Start | - |
* | Write | (reg_addr) |
* | Write | (reg_data[0]) |
* | Write | (....) |
* | Write | (reg_data[len - 1]) |
* | Stop | - |
* |------------+---------------------|
*/
return rslt;
}

Using NRF52840 related library functions to achieve the I2C read-write program as follows:

int8_t user_i2c_read(u8 dev_id, u8 reg_addr, u8 *reg_data, u16 len)
{
ret_code_t err_code =
nrf_drv_twi_tx(&m_twi,dev_id,®_addr,1,false);
APP_ERROR_CHECK(err_code);
err_code = nrf_drv_twi_rx(&m_twi,dev_id,reg_data,len);
APP_ERROR_CHECK(err_code);
return err_code;
}
#define MAX_WRITE_LENGTH 200
int8_t user_i2c_write(u8 dev_id, u8 reg_addr, u8 *reg_data, u16 len)
{
ret_code_t err_code;
uint8_t write_data[MAX_WRITE_LENGTH];
if(len>MAX_WRITE_LENGTH-1)
{
err_code = 1;
return err_code;
}
write_data[0] = reg_addr;
memcpy(&write_data[1],reg_data,len);
err_code = nrf_drv_twi_tx(&m_twi,dev_id,write_data,len+1,false);
APP_ERROR_CHECK(err_code);
return err_code;
}

The related implementation method is shown in the above two programs.
See again the operation program in the main library function to initialize BME280:

struct bme280_dev dev;
int8_t rslt = BME280_OK;
dev.dev_id = BME280_I2C_ADDR_SEC;
dev.intf = BME280_I2C_INTF;
dev.read = user_i2c_read;
dev.write = user_i2c_write;
dev.delay_ms = user_delay_ms;
//before you init bme280, you can choose to do a selftest
rslt = bme280_crc_selftest(&dev);
if(rslt == 0)
{
NRF_LOG_INFO("BME280 self test pass\r\n");
NRF_LOG_FLUSH();
}
rslt = bme280_init(&dev);
if(rslt == 0)
{
NRF_LOG_INFO("Init Success\r\n");
NRF_LOG_FLUSH();
}
else
{
NRF_LOG_INFO("Init Fail,Please Check your address or the wire you
connected!!!\r\n");
NRF_LOG_FLUSH();
while(1);
}
/*
Using normal mode to read the data
*/
stream_sensor_data_normal_mode(&dev);

In the program, a bme280_dev structure variable is defined at first. Then, the structure variable is initialized and assigned, and pass the implemented function name to the corresponding function pointer. Next, enter to initialize the self-test function bme280_crc_selftest (), If the initialization self-test function passes, the output data of bme280 is normal, and the next initialization operation is continued. When the initialization operation is completed, the stream_sensor_data_normal_mode (& dev) function is called to read the bme280 sensor register value and calculate it. Finally, the bme280_get_sensor_data () function and print_sensor_data () function are continuously called in the stream_sensor_data_normal_mode () function to obtain and print the bme280 sensor data continuously. Notice that the program only needs to override the user_i2c_read (), user_i2c_write (), and user_delay_ms () functions to fetch and print the data.

7.1.5 I2C Reads MPU6050 data

In the demo of I2C reading MPU605 data, we mainly explain MPU6050 bottom drive function implementation.
The implementation of I2C read-write, I2C write and other functions is as follows:

u8 IIC_Write_1Byte(u8 SlaveAddress,u8 REG_Address,u8 REG_data)
{
ret_code_t err_code = user_i2c_write(SlaveAddress, REG_Address,
®_data, 1);
return err_code;
}
u8 IIC_Read_1Byte(u8 SlaveAddress,u8 REG_Address,u8 *REG_data)
{
ret_code_t err_code = user_i2c_read(SlaveAddress, REG_Address,
REG_data, 1);
return err_code;
}
u8 IIC_Write_nByte(u8 SlaveAddress, u8 REG_Address, u8 len, u8 *buf)
{
ret_code_t err_code = user_i2c_write(SlaveAddress, REG_Address,
buf, len);
return err_code;
}
u8 IIC_Read_nByte(u8 SlaveAddress, u8 REG_Address, u8 len, u8 *buf)
{
ret_code_t err_code = user_i2c_read(SlaveAddress, REG_Address,
buf, len);
return err_code;
}

It can be seen from the program that the correlation function is through user_i2c_read () function and user_i2c_write () function, which can realize the related bottom I2C read-write function. So the upper application can be more convenient to transplant, improving the reuse rate of the program.

7.2 Hardware Design

The hardware design related to the I2C interface is explained below. In the NRF52840 Eval Kit, the I2C interface of the Arduino interface is usually used to connect the peripherals. The relevant schematic diagram is as follows:
7.3-1.png

The I2C pin allocation in this design is consistent with the official SDK pin allocation, and this I2C pin allocation is as follows:
7.3-2.png
Since the I2C interface of NRF52840 can be assigned to any pin, if you need to modify the pin allocation of I2C, you can modify it directly, that is, in I2C. h, modify the following parts:

# define SDA_PIN NRF_GPIO_PIN_MAP (0, 26)
# Define SCL_PIN NRF_GPIO_PIN_MAP (0, 27)

Compile and download. After downloading, you can observe the following phenomena:

  • I2C scan from the machine part address demo: Access BME280, download 006_I2C (Scan Device) program, open the serial debugging assistant, select the corresponding serial port, reset, will display the following data

7.3-3.png


In this experiment, the device address of BME280 was scanned and will be displayed through OLED, as shown in the following figure:
7.3-4.png

  • I2C reads BME280 data demo: Access BME280 and download 007_I2C (BME280) program. After downloading, the following data will be displayed on OLED:

7.3-5.png

  • I2C reads MPU6050 data demo: Access MPU6050 and download 008_I2C (MPU6050 3D COUBE) program. After downloading, the following data will be displayed on OLED (cube 3D display is not stable yet):

7.3-6.png

8. NFC

This chapter will introduce the use of NFC (Near Field Communication) of NRF52840, mainly about how to start the mobile APP experiment through NFC, and demonstrate the basic use of NRF.
Applications required for this demo: 022-NFC (Launch APP)

8.1 Software Design

8.1.1 Introduction to SDK

The demo of NFC launching mobile App shows how to use an NFC antenna to launch an application on an NFC-enabled device running Android (4.0 or later) or Windows Phone (8.0 or later).
When the demo runs, it initializes the NFC tag and generates an NDEF message with an AAR and Windows LaunchApp record, both of which are prepared to start the nRF Toolbox application. Then, the message is used to set the NFC library function to sense the external NFC. The only event that this program handles is the NFC.
This demo demonstrates the basic usage of the Launch app message generation module:
The messages of NFC launching APP contains two records: the Android Application Record (AAR) and the Windows LaunchApp Record. These records launch applications on Android devices and Windows Phone devices respectively. To start the application on either device, both records must be included in the message. You can also generate a message containing only one of these records, which is only applicable to Android or Windows Phone. The Android Application Record (AAR) contains a string with the Android package name. The Windows LaunchApp record contains a string with the Windows application ID.
This demo comes from the official SDK and has been sorted into the data package: 022-NFC (Launch APP)

8.1.2 Introduction to Library Function

In the NFC library function of NRF52840, the official only provides lib file, but does not provide complete source file. In SDK, the path of lib file is:\ components\ nfc\ t2t_lib\ nfc_t2t_lib_keil. lib. Below, we will mainly introduce the related use of this lib file:

  • Libraries Function: nfc_t2t_setup ();
ret_code_t nfc_t2t_setup (nfc_t2t_callback_t callback, void *
P_context);

This is NFC initial function.
The libraries function has two parameters, which are

//@ param [in] callback function pointer to the callback.

This parameter is a function pointer to the interrupt callback function of NFC, which will be triggered when an NRF device approaches

//@ param [in] p_context Pointer to a memory area used by the callback
//for execution (optional).

This parameter is the parameter of the interrupt callback function passed in.
libraries function: nfc_launchapp_msg_encode ();

ret_code_t nfc_launchapp_msg_encode (uint8_t const *
p_android_package_name, uint8_t android_package_name_length, uint8_t
Const *p_win_app_id, uint8_t win_app_id_length, uint8_t *p_buf,
uint32_t * p_len);

It is a function that encodes NFC information.
It has six parameters, which are:

//@ param [in] p_android_package_name, Pointer to the Android package
name string.If NULL, the Android Application Record will be skipped.

This parameter is a character pointer to the name of the Android app

//@ param [in] android_package_name_length, length of the Android
package name.

This parameter is the character length of the Android app name

//@ param [in] p_win_app_id, Pointer to the Windows application ID

String (GUID). If NULL, the Windows LaunchApp record will be skipped.
This parameter is a character pointer to the name of the Windows application

//@ param [in] win_app_id_length, length of the Windows application ID.
//@ param [out] p_buf, Pointer to the buffer for the message.

This parameter is the character length of the name of the Windows application

//@ param [in, out] p_len, Size of the available memory for the message

As input.

//Size of the generated message as output.

This parameter can be used as an input or as an output, indicating the length of the available buffer, or as an output, the length of the encoded information.
Library function: nfc_t2t_payload_set ();
This function writes the encoded information to the NFC side

ret_code_t nfc_t2t_payload_set (const uint8_t * p_payload, size_t payload_length);

This function takes two parameters, which are:

//@ param [in] p_payload Pointer to the memory area in RAM
//Containing the payload to send.

This parameter is the first address of the encoded buffer

//@ param [in] payload_length Size of the payload in bytes.

This parameter is the length of the encoded buffer
Library function: ret_code_t nfc_t2t_emulation_start ();
The function of this parameter is to start NFC transmission. If there is no parameter, it can be called directly.

8.1.3 NFC Starts APP

The following will introduce the demo for NFC to start the APP:
First, store the name of the APP in an array:
Andoid Phone APP name:

static const uint8_t m_android_package_name [] =
{'N', 'O', '.', 'N', 'O', 'R', 'D', 'I', 'C', 'S',
'E', 'M', 'I', '.', 'A', 'N', 'D', 'R', 'O', 'I',
'D', '.', 'N', 'R', 'F', 'T', 'O', 'O', 'L', 'B',
'O', 'X'};

Windows Phone APP name:

static const uint8_t m_windows_application_id [] =
{'{', 'e', '1', '2', 'd', '2', 'd', 'a', '7', '-',
'4', '8', '8', '5', '-', '4', '0', '0', 'F', '-',
'B', 'C', 'D', '4', '-', '6', 'C', 'B', 'D', '5',
'B', '8', 'C', 'F', '6', '2', 'C', '}'};

Define an initialization callback function, which will be entered when an NFC contact is detected, and LED0 on the NRF52840 Eval Kit will be turned on when it is close to the NFC contact, and LED0 on the NRF52840 Eval Kit will be turned off when it is far away from the NFC contact.
The callback function is as follows:

static void nfc_callback (void * p_context, nfc_t2t_event_t event,
const uint8_t * p_data, size_t data_length)
{
(void) p_context;
switch (event)
{
case NFC_T2T_EVENT_FIELD_ON:
bsp_board_led_on (BSP_BOARD_LED_0);
break;
case NFC_T2T_EVENT_FIELD_OFF:
bsp_board_led_off (BSP_BOARD_LED_0);
break;
default:
break;
 }
}

In the main function, the process to start NFC is:
1. Configure interrupt callback function and initialize NFC;
2. Encoding NFC information;
3. Loading the NFC information to the NFC tag;
4. Start NFC;
The procedure is as follows:

int main (void)
{
uint32_t len;
uint32_t err_code;
//Init log
log_init ();
//Init led
bsp_board_init (BSP_INIT_LEDS);
//Set NFC with a callback
err_code = nfc_t2t_setup (nfc_callback, NULL);
APP_ERROR_CHECK (err_code);
//provide available buffer size for encoding function
len = sizeof (m_ndef_msg_buf);
//Encode launchapp message into buffer
err_code = nfc_launchapp_msg_encode (m_android_package_name,
sizeof (m_android_package_name),
m_windows_application_id,   
sizeof (m_windows_application_id),
m_ndef_msg_buf,
& len);
APP_ERROR_CHECK (err_code);
//set created message as the NFC payload
err_code = nfc_t2t_payload_set (m_ndef_msg_buf, len);
APP_ERROR_CHECK (err_code);
//start sensing NFC field
err_code = nfc_t2t_emulation_start ();
APP_ERROR_CHECK (err_code);
while (1)
{
NRF_LOG_FLUSH ();
__WFE ();
 }
}

8.2 Hardware Design

In this hardware design, the relevant pins of NFC interface cannot be redistributed, and the NRC hardware design is compatible with the official SDK. The relevant schematic diagram of NFC design is as follows:
8.2.png
Its pins are:
8.2-1.png
Test demos: First, turn on NFC on the mobile phone (which needs mobile phone support). And the mobile phone needs to install nRF Toolbox APP, the Android APP has been saved in the data package, and Apple needs to download it from the App Store. After installing the App, connect the NFC coil, compile and download it. When the download is completed, bring the NFC end of the mobile phone close to the NFC coil. At this time, the application nRF Toolbox APP on the mobile phone will start automatically, and at the same time, LED1 on the development board will be turned on. If bring the NFC end of the mobile phone far away from the NFC coil, the LED1 on the development board will be turned off.

9. Bluetooth

This chapter will introduce the use of Bluetooth, and will introduce the use of Bluetooth slave, Bluetooth host and Bluetooth master-slave integrated machine respectively. Related demos see Part-2-Bluetooth-Slave-Device, Part-3-BluetoothMaster-Device, Part-4-Bluetooth-Master & Slave-Device.

9.1 Experiment Preparation

Before the experiment, it is necessary to build the relevant operating environment and prepare the relevant hardware.

9.1.1 Development Environment

First, the following tools should be installed in the development environment:

  • MDK5.25: Note that the hex file size generated by compiling an inactivated MDK pair cannot exceed 256K, and note that MDK is activated.
  • Jlink driver: In addition to downloading and debugging programs, Jlink driver is also recognized by nRFx-Command-LineToools, which is used to erase Flash. When downloading is abnormal, erasing Flash will have a good effect.
  • nRFx-Command-Line-Toools: This tool is mainly used to erase Flash. Usually, when downloading Bluetooth related programs again, it is necessary to erase Flash once, download SoftDevice first, and then download Bluetooth programs.
  • Mobile phone test software: nRF Toolbox
  • Apple phone (IPhone4S and above) or Android phone (mobile phone hardware supports BLE, and Android system is 4.3 and above). For other related matters needing attention and detailed steps, please refer to "Chapter 2 Development Environment Setup".

9.1.2 Download Bluetooth Protocol Stack

Because Nordic's nRF52840 separates the Bluetooth protocol stack (SoftDevice) from the application,
Therefore, the download needs to be divided into two parts to download.

  • Erase Flash

The program without Bluetooth function does not need to download the Bluetooth protocol stack (SoftDevice). If the Bluetooth protocol stack (SoftDevice) has been downloaded, the program without Bluetooth function needs to be downloaded.
Otherwise, the following prompt will appear when downloading:
Bluetooth.png
Among the demos provided, the following are the demos with Bluetooth protocol stack (SoftDevice) and without Bluetooth protocol stack (SoftDevice):
Pic d.png

  • Download Bluetooth protocol stack

Erase Flash first. You can erase Flash through nRFx-Command-Line-Tools. After installation according to the steps in Chapter 2, open the CMD console and enter the following command to erase Flash:
9-1.png
If you fail to erase Flash, as shown in the following figure:
9-2.png
You can try to erase with SEGGER J-Flash Lite V6.34g, which can be found in the Start menu if Jlink is installed:
9-3.png
You need to use Jlink (ARM Debugger) to connect NRF52840 Eval Kit to PC, and then open the tool to identify the device, as shown in the following figure:
9-4.png
Click OK to enter, and then click Erase Chip to erase Flash, as shown in the following figure:
9-5.png
After erasing Flash, you need to download the Bluetooth protocol stack. Keil is recommended to download the Bluetooth protocol stack. The download method is as follows:
Choose the demo with SoftDevice (that is, the demo with Bluetooth protocol stack) and open it with Keil, for example, open the demo with Bluetooth SerialNet this time, and select flash_s140_nrf52_6.1.0_softdevice in the Project Targets box
9-6.png
After selecting, click Load to download the Bluetooth protocol stack:
9-7.png
After the Bluetooth stack is downloaded successfully, it can be downloaded once as long as Flash is not erased. If Flash is erased later and demos with Bluetooth protocol stack (SoftDevice) are continued, the protocol stack needs to be downloaded again

9.2 Bluetooth Slave Experiment

9.2.1 Bluetooth Serial Transmission

Download: 

  • Prepare for the corresponding experiment in 9.1.
  • Enter the Bluetooth Host SerialNet Application Keil Project folder, which is located in the Part-2-Bluetooth-Slave-Device\USER path.
  • Open the SlaveDevice-Bluetooth-To-UART (APP) demo with Keil, click the compile button to compile the project, observe the compilation output bar, and modify the program if there are errors or warnings until the compilation is successful. The compiled HEX file is located in the TEMP folder.
  • Click the "Load" to download

Experiment demonstration:

  • After the program is downloaded and run, the indicator light LED1 on the board flashes to indicate that it is broadcasting.
  • Turn on Bluetooth on the mobile phone.
  • Open the nRF Toolbox on your phone and click to enter UART, as shown below:
  • Click Connect to automatically scan available Bluetooth, and click Nordic_UART to connect, as shown in the following figure:

9-8.png

  • After the connection is successful, the indicator light LED1 on the board will always be on, indicating that the connection has been established with the host (mobile phone).
  • Edit the data to be sent:

9-9.png
After editing, click DONE to complete the data editing.

  • Next, the mobile phone can be used to send data to the development board. After receiving the data, the development board will automatically forward it to the serial port. Click 123456789 in turn, and the serial port debugging assistant will receive the following data:

F.png
At this time, the receiving window of the serial debugging assistant on the PC can see the data sent by the mobile phone to the development board through Bluetooth.

  • In addition, in the upper right corner of the APP, there are 3 points. After clicking, click Show log to view the communication record between the mobile phone and the development board through Bluetooth:
  • At this time, data can be sent to the mobile phone APP through the serial debugging assistant, as shown in the following figure:

PicG.png

The above demonstrates the process of sending and receiving data between PC serial debugging assistant and mobile APP through Bluetooth.

9.2.2 Bluetooth Anti-loss

Download:

  • Prepare for the corresponding experiment in 9.1.
  • Enter the Bluetooth Host SerialNet mode application Keil Project folder, which is located in the Part-2-Bluetooth-Slave-Device\ USER path.
  • Open the SlaveDevice-Bluetooth-Proximity (APP) demo with Keil, click the "compile button" to compile the project, observe the compilation output bar, and modify the program if there are errors or warnings until the compilation is successful. The compiled HEX file is located in the TEMP folder.
  • Click the Download button to download.

Experimental Demonstration:

  • After the program is downloaded and run, the indicator light LED1 on the board flashes to indicate that it is broadcasting.
  • Turn on Bluetooth on the mobile phone.
  • Open the nRF Toolbox on your phone and click to enter UART, as shown below:
  • Click Connect to automatically scan available Bluetooth, and click Nordic_UART to connect, as shown in the following figure:

9-12.png

  • After the connection is successful, the indicator light LED1 on the board is always on, indicating that the connection has been established with the host (mobile phone).
  • After successful connection, the following interface will be displayed:

E.png
At this time, click the indicator control button on APP to control the level of P0.15 pin on the development board. When observing the experiment phenomenon, pin P0.15 can be connected to L3 through DuPont line, and the on and off of indicator LED3 can be observed. Click the Delete button to delete the current device.

  • At this time, press the key S1 on the development board, and the mobile phone will play a ringtone; Press the button S1 again, and the phone will stop playing the ringtone.
  • If the mobile phone is far away from the development board, when it detects that the development board leaves the receiving range of the Bluetooth BLE signal of the mobile phone, it will give a prompt message, as shown in the following figure:

9-14.png

9.2.3 Bluetooth Beacon (Support WeChat shake)

Beacon can build a small information base station by using low-power Bluetooth technology, which can be applied to all activities related to people's indoor flow, such as indoor navigation, mobile payment, in-store shopping guide, flow analysis, and item tracking.
Beacon is not the standard specified by Bluetooth SIG. Common specified standards are Apple's iBeacon and Google's Eddystone.
Download:

  • Prepare for the corresponding experiment in 9.1.
  • Enter the Bluetooth Host SerialNet Application Keil Project folder, which is located in the Part-2-Bluetooth-Slave-Device\ USER path.
  • Open the SlaveDevice-Bluetooth-BEACON (WeChat) demo with Keil, click the "compile" button to compile the project, observe the compilation output bar, and modify the program if there are errors or warnings until the compilation is successful.

The compiled HEX file is located in the TEMP folder.

  • Note: this demo has been modified on an official basis compared to the official SDK (ble_app_beacon), mainly (lines 74-77):
APP_COMPANY_IDENTIFER modified to: 0X004c
APP_MAJOR_VALUE modified to: 0x00, 0x0A
APP_MINOR_VALUE modified to: 0x00, 0x07
APP_BEACON_UUID is modified to: 0xFD, 0xA5, 0x06, 0x93,\
                                0xA4, 0xE2, 0x4F, 0xB1,\
                                0xAF, 0xCF, 0xC6, 0xEB,\
  • Click “Load”to download. 

Experiment demonstration:

  • First, open WeChat in your phone, enter and shake it. Since there is no iBeacon device around, the peripheral options will not be displayed, as shown in the picture below.
  • After the program is downloaded and run, the indicator LED1 on the board flashes to indicate that it is broadcasting.
  • At this time, open WeChat again, enter it and shake your phone. The iBeacon device will be detected and the peripheral options will be displayed, as shown in the figure below:

9-15.png

  • At this time, shake your phone, you will get the nearby information, click to enter, the page after entering is as shown in the picture:

9-17.png
Note: The web page detected is configurable. For details, please see the official guide of WeChat: Https://zb.weixin.qq.com/intro.xhtml

  • The above is an example of WeChat shaking. In addition, this experiment is the open test ID of WeChat, as follows:

9-18.png

9.2.4 Bluetooth Mouse

In this experiment, the mouse is realized by HOGP profile (HID over GATT Profile). HOGP uses the basic protocol GATT of BLE to realize the interaction between HID host and Device.
Download:

  • Prepare for the corresponding experiment in 9.1.
  • Enter the Bluetooth Host Application Keil Project folder, which is located in the Part-2-Bluetooth-Slave-Device\ USER path.
  • Open the SlaveDevice-Bluetooth-HIDS-MOUSE (APP) demo with Keil, click the compile button to compile the project, observe the compilation output bar, and modify the program if there are errors or warnings until the compilation is successful. The compiled HEX file is located in the TEMP folder.
  • Click to download.

Experimental Demonstration:

  • After the program is downloaded and operated, the indicator LED1 on the board flashes to indicate that it is broadcasting.
  • At this time, turning on Bluetooth on the mobile phone for search for Nordic_Mouse device and connect. After the connection between the mobile phone and NRF52840 Eval Kit is established, LED1 will always be on.
  • At this point, connect P0.11, P0.12, P0.24 and P0.25 to the buttons respectively (press grounding), as shown in the following figure:

9-19.png
After pressing the button, the mouse movement will be displayed on the mobile phone screen. The related pins and their functions are shown in the following table:
9-20.png
The corresponding effect is shown in the following figure:
9-21.png

  • If PC has Bluetooth and its Bluetooth supports BLE, it can realize the same function and operate with the mobile phone.
  • If you need to use Joystick on the Arduino Extension Pad (Accessory Shield) as the mouse control button, you need to make the following modifications:

9-22.png

9.2.5 Bluetooth Keyboard

In this experiment, HOGP profile (HID over GATT Profile) is used to realize the keyboard. HOGP uses the basic protocol GATT of BLE to realize the interaction between HID host and Device.
In this experiment, after the development board is connected with the host computer (mobile phone or computer), press KEY1 key on the development board to simulate keyboard input, open a notepad or other input window on the mobile phone or computer and let it be in the input state. After pressing KEY1 key, the letter "hello" will be input one by one. If Bluetooth is connected to the PC, press the "CapsLock" key on the computer keyboard at this time, turn on the uppercase, and the pin corresponding to P0.15 on the development board will output a low level. Turn uppercase off, and the pin corresponding to P0.15 on the development board will output high level (pin P0.15 can be connected to L3 through DuPont line to observe the experimental phenomenon).
Download: 

  • Prepare for the corresponding experiment in 9.1.
  • Enter the Bluetooth Host Application Keil Project folder, which is located in the Part-2-Bluetooth-Slave-Device\ USER path.
  • Open the SlaveDevice-Bluetooth-HIDS-KEYBOARD (APP) demo with Keil, click the compile button to compile the project, observe the compilation output bar, and modify the program if there are errors or warnings until the compilation is successful. The compiled HEX file is located in the TEMP folder.
  • Click "Load"to download.

Experiment demonstration:

  • After the program is downloaded and run, the indicator LED1 on the board flashes to indicate that it is broadcasting.
  • At this time, turn on Bluetooth on the mobile phone, search for Nordic_Keyboard device and connect. After the connection between the mobile phone and NRF52840 Eval Kit is established, LED1 will always be on.
  • At this time, open any text input box, and this experiment opens the WeChat text input box.
  • After the mobile phone opens the text input box, press KEY1 (P0.13) several times, and enter "h", "e", "l", "l" and "o" in turn, as shown in the following figure:

9-23.png

9.2.6 CSCS Bicycle Speed and Rhythm (Simulated Data)

The CSCS bicycle speed and pace (analog data) experiment demonstrates that the development board sends data such as speed, pedal frequency, riding distance, accumulated riding distance and gear ratio to the mobile phone through BLE.
Among them, the sent data is simulated by software, which is sent once every second based on Cycling Speed and Cadence profile. When the development board is connected with the mobile phone, the APP (nRF Toolbox) on the mobile phone will display the data changes.
Download:

  • Prepare for the corresponding experiment in 9.1.
  • Enter the Bluetooth Host Application Keil Project folder, which is located in the Part-2-Bluetooth-Slave-Device\ USER path.
  • Open the BlueTooth-CSCS (APP) demo with Keil, click the compile button to compile the project, observe the compilation output bar, and modify the program if there are errors or warnings until the compilation is successful. The compiled HEX file is located in the TEMP folder.
  • Click the Download button to download.

Experimental demonstration:

  • After the program is downloaded and run, the indicator LED1 on the board flashes to indicate that it is broadcasting.
  • Open the nRF Toolbox and click to enter CSC (Cycling Speed and Cadence), as shown in the following left figure:
  • Click Connect to automatically scan available Bluetooth, and click Nordic_CSC to connect, as shown in the following figure:

9-24.png

  • After the connection is successful, the bicycle speed and other related data will be displayed on the mobile APP.

9-25.png

9.3 Bluetooth Host Experiment

9.3.1 Master-slave Heart Rate Meter (Simulated Data)

In this master-slave heart rate meter experiment, two development boards are used, one of which is used as a master and the other as a slaver.
Download: In this experiment, we download by master device and slaer device respectively.

  • Both master and slaver development boards need to prepare well according to 9.1.
  • Enter the Keil project folder of Bluetooth host application program, which is located in Part-3-Bluetooth-Master-Device\ USER path, where the demo of the master device is Master-Link-ToSlave-By-HRS (Master) and the slaver demo is Master-Link-To-Slave-By-HRS (Slaver)
  • Open the demos of master device and slaver respectively, click the compile button to compile the project, observe the compilation output bar, and modify the program if there are errors or warnings until the compilation is successful. The compiled HEX file is located in the TEMP folder.
  • Download the master program and slaver program to the corresponding development board.

Experimental demonstration:

  • First, the schematic diagram of communication between master and slaver is as follows:

9-26.png

  • After downloading, power on the master device and slaver. When the master device and slaver programs are running, the master device will auto-link to slaver. After the master device connects with the slaver successfully, it can be observed that LED1 of the master device and slaver will light up, indicating that the connection has been successfully established.
  • After that, the Slaver will send data to Master, and Master will send the data to the PC through the serial port after receiving the data. The data is shown in the following figure, which is the blood glucose meter data sent by Slaver to Master:

9-27.png

9.4 Bluetooth Master-slave Integration Experiment

9.4.1 BLE Relay Experiment

In this experiment, we will demonstrate that the development board works in the master-slave integration mode:

  • When the development board is used as the master, it will actively connect with a development board that downloaded RSCS running speed and pace program.
  • When the development board is used as slaver, it will be connected with the mobile phone.
  • In the master-slave integration, Bluetooth relay connects the slaver as a master and receives the data sent by the slaver; At the same time, as a slaver, it sends the received data to the mobile phone, as shown in the following figure:

9-28.png

In this experiment, at least two development boards are needed, one of which is an RSC slaver and one of which is a Relay.
In addition, Realy and Device are defined:
Realy: As a Master and Slaver. As a Master, you can connect with slaver devices and receive data sent by slaver devices. As a slaver, you can connect with mobile phones and send data to mobile phones.
Seneor: As a slaver, in this experiment, it can be RSC (running speed and pace) or HRM (heart rate meter) experimental program.
Download:
In this experiment, we download by master device and slaver device.

  • Both the master and slaver development boards need to prepare for the corresponding experiments in 9.1.
  • Enter the Bluetooth master application Keil project folder, where the master demo is located under the Bluetooth-Master & Slave-Device\ USER path, the demo is Master & SlaverReally (Master), and the slaver demo is Master & Slave-Realy (Slaver)
  • Open Master and Slaver demos respectively, click the compile button to compile the project, observe the compilation output bar, and modify the program if there are errors or warnings until the compilation is successful. The compiled HEX file is located in the TEMP folder.
  • Download the Master program and Slaver program to the corresponding development board.
  • Note: In this experiment, the slaver program is RSC (running speed and pace). In addition, the slaver program can also be HRM (heart rate meter), as shown in the following figure:

9-29.png
Experiment Demonstration:

  • First, power on Relay. When the program runs, the indicator LED1 and LED3 are always on, indicating that Master is scanning and the slaver is broadcasting.
  • Then power on the Device. After running, LED1 starts flashing, indicating that is broadcasting, and then LED1 is always on, indicating that the Device has established a connection with Master.

Relay Indicator Description:
9-30.png
Note: LED3 is not compatible with the official SDK at this time. When doing this experiment, L3 should be connected to P1.05 by DuPont line, as shown in the following figure:
9-31.png
Device Indicator Description:
9-32.png

  • Next, use the mobile phone to connect the Relay slave. Open the nRF Toolbox in your phone, clicks RSC and connect, choose nRF Relay to connect. After connection, LED3 on Relay turns off and LED4 turns on. At this time, the mobile phone will receive the data forwarded by Relay from Seneor, as shown in the following figure:

9-33.png
At the same time, the serial debugging assistant will output relevant data:
9-34.png

10. Bluetooth MESH

In this chapter, we describe some of the basic concepts of the Bluetooth Mesh network using Nordic's nRF5 SDK for Mesh. The project we used here is light-switch examples from the official MESH SDK will be used for demonstration. For more detailed operations, please refer to the official Bluetooth MESH SDK and its documents.
The Bluetooth Grid Profile specification was developed and published by Bluetooth SIG. It allows one-to-one, one-to-many, and many-to-many communications, and it uses the BLE protocol to exchange messages between nodes on the network. Nodes can communicate with each other as long as they are in direct radio range with each other, or as long as there are sufficient devices available to listen and forward these messages. End-user applications (such as lamp control) are defined with the help of the client-server grid model defined in the grid model specification. The switch on and off light sample program(light-switch examples) demonstrate the main parts of Bluetooth networking.
This demo contains the following subroutine:
Light Switch Server:It is a simple server and implements a Generic OnOff server mode model, which is used to receive status data and control LED1 on and off.
Light Switch Client:It is a simple client, which implements four Generic OnOff client mode models. When the user presses any one of the four keys, the on-off signal will be sent to the set target address.
Mesh Provisioner:It is a simple distributor. The distributor connects all nodes in the network. In addition, the distributor configures the binding and publishing, and subscription settings of grid model instances on these nodes to enable distribution network devices to communicate with each other.
These three demos will be used as the running programs of client, server, and distributor respectively.
This time, the four buttons of the NRF52840 Eval Kit will be used for related operations, and the four LEDs will reflect the corresponding status of related operations.
Network Distributor:
KEY1: Start the distribution network
LED1 on: Distribution network in progress
LED2 Bright: Set up the distribution network
Client:
In the process of distribution network:
LED1-LED4: Flashing 4 times indicates that the distribution network has been completed, and after the distribution network settings are completed:
KEY1: Send a message to an odd array of addresses (Address: 0xc003) to open its LED1
KEY2: Send a message to the address odd array (Address: 0xc003) to turn off its LED1
KEY3: Send a message to an even array of addresses (Address: 0xc002) to open its LED1
KEY4: Sends a message to an even array of addresses (Address: 0xc002) to shut down its LED1 server: In the process of distribution network: LED1-LED4: Flashing 4 times indicates that the distribution network has been completed. After the distribution network and distribution network settings are completed: LED1: Reflects the state of the variable OnOff (LED lights up when low) LED1 ON: OnOff has a value of 0
Server side:
In the process of network distribution:
LED1-LED4: Flashing 4 times indicates that the distribution network has been completed
After connecting to the network and the settings are completed:
LED1: Reflects the state of the variable OnOff (LED lights up when low)
LED1 Bright: the value of OnOff is 0
LED1 off: the value of OnOff is 1.
The following figure shows an overall view of the mesh network that we will set up in this demonstration. The numbers in parentheses indicate the addresses assigned to these nodes by the distributor.
10-1.png
The MESH network diagram is shown in the following figure:
10-2.png
Hardware requirements:
At least 3 NRF52840 Eval Kit development boards are required to run this demo.

  • 1 development board to run client demo 
  • 1 development board to run distributor demo 
  • at least 1 development board to run server demo 

Software requirements:
1. nRF Mesh SDK: nrf5_SDK_for_Mesh_v2.2. 0_src, download and unzip the SDK
2. BLE SDK: nRF5_SDK_15.0. 0_a53641a, download and unzip the SDK
3. nrfjprog, recommended for brushing Flash, can be downloaded and installed using nRFx Command Line Tools for Windows.
4. SEGGER Embedded Studio for ARM 4.10 a (Bluetooth MESH demos are created using this IDE).

  • Note: The extracted folder needs to be under a unified path. When compiling, the compiler will actively look for files under BLE SDK, as shown in the following figure, otherwise an error will be reported in the compilation:

Nrf5.png
Download file:
1. Connect NRF52840 Eval Kit to the USB interface of the PC, and pay attention to distinguish server, client, and network distributor.
2. Open the corresponding demo using SEGGER Embedded Studio for ARM 4.10 a.
The distributor demo is located at:
MESH\nrf5_SDK_for_Mesh_v2.2.0_src\examples\light_switch\provisioner\light_switch_provisioner_nrf52840_xxAA_s140_6_0_0.emProject

The server-side demos are located at:
MESH\nrf5_SDK_for_Mesh_v2.2.0_src\examples\light_switch\proxy_server\light_switch_proxy_server_nrf52840_xxAA_s140_6_0_0.emProject

The Client demos are located at:
MESH\nrf5_SDK_for_Mesh_v2.2.0_src\examples\light_switch\proxy_client\light_switch_proxy_client_nrf52840_xxAA_s140_6_0_0.emProject

3. After opening the corresponding demo, compile the associated demo:
Click
Build-> Build light_switch_provioner_nrf52840_xxAA_s140_6.00, or directly press the keyboard shortcut key F7 to compile, as shown in the following figure:
F7.png
4. Download demo:
Click
Target-> Download light_switch_visioner_nrf52840_xxAA_s140_6.0.0 to download
Target52.png
5. You can also debug:
Click
Debug-> go in turn to debug, or directly press the shortcut key F5 to debug, as shown in the following figure:
Nrf52805.png
Related operations of this demo:
After the network distributor, client, and server download the corresponding demos,
1. Power up all devices and press the reset button to reset.
2. Operation of distributor: Press KEY1 of the distributor to start the distribution network, distributor first distributes the network and configures the client, and distributes address 0x100 to the client node; Then connect the server, assigns 0x101 address to the first server, assign 0x102 address to the second server, and so on. In this process, the client node address and server node address are recorded, and the server node address is divided into an odd array and an even array.
3. After the LED1 on the distributor lights up stably for a while, it means that all undistributed devices have been connected to the network. Now, the on-off state of LED1 on the server can be changed by pressing buttons on the client.
4. Press KEY1: Send Message to Address Odd Array (Address: 0xc003) to open LED1
5. Press KEY2: Send Message to Address Odd Array (Address: 0xc003) to close LED1
6. Press KEY3: Send Message to Address Even Array (Address: 0xc002) to open LED1
7. Press KEY4: Send Message to Address Even Array (Address: 0xc002) to close LED1
8. During this process, you can connect the distributor and the client through the J-Link RTT viewer to observe the relevant data output, as shown in the following figure:
Nrf6.png
The above is a simple example of Bluetooth Mesh.
In addition to Bluetooth devices, the network distributor can also be a mobile phone. Next, we will explain how to use the mobile APP as the network distributor for network distribution and follow the steps:
1. Download the corresponding client and server programs to the corresponding development board.
2. Download nRF Mesh app on your mobile phone (Android or IOS) as a network distributor.
3. The mobile phone is used as a network distributor to connect the client and the server.
4. Set the server controlled by keys on the mobile phone.
5. Press KEY1 on the client and LED1 on the server.
6. Press KEY2 on the client to extinguish LED1 on the corresponding server.
The program execution process will be introduced below
The Network Distribuor Program Execution Flow:
The network distributor connects and configures network nodes to set up the Bluetooth mesh network, which implements the multi-layer protocol of the Bluetooth MESH network.
The network distributor first uses the known UUID to network and configure the client device, and then networks and starts to configure the server device.
The following picture shows a typical distributor distribution network and the process of configuring the client server:
Nrf7.png
Client Program Execution Flow:
In MESH, the client plays a controlling role in the MESH network. The client has 4 KEY to control the LED1 on and off of the server. The program instantiates 2 general OnOff client objects, and the network distributor configures the client to communicate with the server.
Server-side Program Execution Flow:
The server-side demo initializes a generic OnOff server object to control the state of LED1. The network distributor configures the server to communicate with the client, and when the LED state of the server changes, it will send information to the client. The initialization process of the server is shown in the following figure:
Nrf8.png

Resources

Documentation

Software

Android APP

Keil DeviceFamilyPack

Support



Technical Support

If you need technical support or have any feedback/review, please click the Submit Now button to submit a ticket, Our support team will check and reply to you within 1 to 2 working days. Please be patient as we make every effort to help you to resolve the issue.
Working Time: 9 AM - 6 PM GMT+8 (Monday to Friday)