nRF Connect SDK Intermediate

Changing the version will not affect your certificate
Lesson 1 – Zephyr RTOS: Beyond the basics
7 Topics | 1 Quiz
Boot-up sequence & execution context
Thread life cycle
Scheduler in-depth
Data passing
Exercise 1 – Exploring threads and ISRs
Exercise 2 – Kernel options
Summary
Lesson 1 quiz
Lesson 2 – Debugging and troubleshooting
8 Topics | 1 Quiz
Debugging in nRF Connect for VS Code
Build errors and fatal errors
Troubleshooting the devicetree
Physical debugging
Exercise 1 – Advanced debugging in nRF Connect for VS Code
Exercise 2 – Debugging with core dump and addr2line
Exercise 3 – Debugging the devicetree
Exercise 4 – Remote debugging with Memfault
Lesson 2 quiz
Lesson 3 – Adding custom board support
5 Topics | 1 Quiz
Board definition
Creating board files
Board files for multi-core hardware & TF-M
Exercise 1 – Custom board for single-core SoC
Exercise 2 – Custom board for a multi-core & TF-M capable SoC/SiP
Lesson 3 quiz
Lesson 4 – Pulse Width Modulation (PWM)
4 Topics | 1 Quiz
Pulse Width Modulation (PWM)
Zephyr PWM API
Exercise 1 – Controlling an LED with PWM
Exercise 2 – Using PWM to control a servo motor
Lesson 4 quiz
Lesson 5 – Serial Peripheral Interface (SPI)
3 Topics | 1 Quiz
Serial Peripheral Interface (SPI)
Zephyr SPI API
Exercise 1 – Interfacing with a sensor over SPI
Lesson 5 quiz
Lesson 6 – Analog-to-digital converter (ADC)
5 Topics | 1 Quiz
ADC peripheral on Nordic devices
Choosing between Zephyr ADC API and nrfx SAADC driver API
Exercise 1 – Interfacing with ADC using Zephyr API
Exercise 2 – Interfacing with ADC using nrfx driver and software timers
Exercise 3 – Interfacing with ADC using nrfx drivers and TIMER/PPI
Lesson 6 quiz
Lesson 7 – Device driver development
6 Topics | 1 Quiz
Device driver model
Device driver implementation
Device power management
Exercise 1 – Creating a custom driver using the sensor API
Exercise 2 – Adding power management to a custom driver
Exercise 3 – Creating a custom driver with a custom API
Lesson 7 quiz
Lesson 8 – Sysbuild
5 Topics | 1 Quiz
Sysbuild explained
Sysbuild configuration
Sysbuild – Partition Manager
Exercise 1 – Configuring extra image
Exercise 2 – Adding custom image
Lesson 8 quiz
Lesson 9 – Bootloaders and DFU/FOTA
12 Topics | 1 Quiz
Bootloader basics
Application verification
Device Firmware Update (DFU) essentials
MCUboot, and relevant libraries
DFU for the nRF5340 SoC
Exercise 1 – DFU over UART
Exercise 2 – DFU with custom keys
Exercise 3 – DFU with external flash
Exercise 4 – DFU over USB
Exercise 5 – FOTA over Bluetooth LE
Exercise 6 – FOTA over LTE-M/NB-IoT
Exercise 7 – FOTA over Wi-Fi
Lesson 9 quiz
Get your Certificate!
Feedback
Feedback

If you are having issues with the exercises, please create a ticket on DevZone: devzone.nordicsemi.com
Drag & Drop Files, Choose Files to Upload You can upload up to 2 files.
Loading
RegisterLog in

Exercise 3 – Creating a custom driver with a custom API

In the previous exercises, we developed a custom driver using the existing sensor driver API. However, in some cases, there may not be an existing subsystem that meets our requirements. In this lesson, we will learn how to create a custom API, configure the devicetree with custom parameters, and finally, use these in the driver and application.

In this exercise, we will create a custom driver used to periodically blink an LED. We want to get an LED (via GPIO pin) device to blink periodically. We also want to make this period configurable from the devicetree.

Based on these requirements, the devicetree should contain the following 2 parameters:

  • The LED’s GPIO pin
  • The blink period

In addition, we want to have the possibility to change the blinking period from the application. Our device driver needs to provide the following 2 API’s:

  • blink_set_period_ms – To change the blinking period.
  • blink_off – To turn off the LED entirely.

Like in exercise 1, we will start with the application template: app, and custom_driver_module, which is almost empty now. As we learned about the Zephyr modules before, our template has been preconfigured already to be included in the build system. Our initial file structure will look like this:

l7_e3/
├─── app/
|     ├─── boards/
│     ├─── src/
│     │    └─── main.c
│     ├──prj.conf
|     └──CMakeLists.txt
|
└─── custom_driver_module/
      ├─── drivers/
      │    ├── blink/
      │    │    ├──gpio_led.c
      │    │    ├──CMakeLists.txt
      │    │    └───Kconfig
      │    ├──CMakeLists.txt
      │    └───Kconfig
      ├─── dts/
      ├─── include/
      │     └───blink.h
      ├─── zephyr/
      │     └───module.yml
      ├──CMakeLists.txt
      └──Kconfig
File structure

Exercise steps

Open the code base of the exercise by navigating to Create a new application in the nRF Connect for VS Code extension, select Copy a sample, and search for Lesson 7 Exercise 3.

Alternatively, in the GitHub repository for this course, go to the base code for this exercise, found in l7/l7_e3.

1. Create the driver binding.

We need a binding file for the driver to define the device driver parameters.

1.1 Create the binding file blink-gpio-leds.yaml.

Create the file blink-gpio-leds.yaml in the dts/bindings directory, and add the following lines to declare the devicetree compatibility name, and include the base for the binding.

Copy
compatible: "blink-gpio-led"

include: base.yaml
YAML

1.2 Add a property for the LED GPIO to the binding.

Add the property led-gpios by adding the following lines to the file.

Copy
properties:
  led-gpios:
    type: phandle-array
    required: true
    description: GPIO-controlled LED.
YAML

led-gpios property will be used to determine the GPIO pin used to connect to the LED. This type of property is used in most SoC peripheral drivers.

Note

You can find more information about the phandle-array type and its role in GPIO definitions in Phandles — Zephyr Project Documentation

1.3 Add a property for the blink period to the binding.

Add the property blink-period-ms for the blink period with the following lines.

Copy
  blink-period-ms:
    type: int
    description: Initial blinking period in milliseconds.
YAML

This is the key parameter used to control the behavior of our driver. In the next steps, we will provide API to modify its value.

2. Define the API’s for the “blink” driver class.

Next, we will create a class for the driver. In other words, we will add a custom class providing a common API for a selected group of device drivers. This is done in the file blink.h found in custom_driver_module/include.

2.1 Define the API structure in the driver class.

Open the include/blink.h file in the custom driver module directory and define the API structure blink_driver_api. Let’s include a pointer to the function that changes the blinking period. We also need to let the toolchain know that this structure is a device driver API by using the __subsystem prefix.

Copy
__subsystem struct blink_driver_api {
	/**
	 * @brief Configure the LED blink period.
	 *
	 * @param dev Blink device instance.
	 * @param period_ms Period of the LED blink in milliseconds, 0 to
	 * disable blinking.
	 *
	 * @retval 0 if successful.
	 * @retval -EINVAL if @p period_ms can not be set.
	 * @retval -errno Other negative errno code on failure.
	 */
	int (*set_period_ms)(const struct device *dev, unsigned int period_ms);
};
C

Important

In this exercise, it is important to use a proper structure name following the pattern [subsystem]_driver_api. In later steps, we will use the DEVICE_API.. macro helpers based on this pattern.

2.2 Implement a public API function for the driver class.

That means we can call this function from an instance of any driver that belongs to this class. Although they have the same API function, the behavior will be specific to a particular driver’s implementation. The API function should follow the naming structure z_impl_<function_name>.

This time, we will use an additional macro helper:

  • DEVICE_API_IS(class, device) – Verifies if the device is a particular class. In our case, it verifies if the function was called with a device whose driver is the blink class.
  • DEVICE_API_GET(class, device) – Gets the pointer to the API instance of a given device class. In our case, it gives access to the blink_driver_api instance defined by the driver
Copy
static inline int z_impl_blink_set_period_ms(const struct device *dev,
					     unsigned int period_ms)
{
	__ASSERT_NO_MSG(DEVICE_API_IS(blink, dev));

	return DEVICE_API_GET(blink, dev)->set_period_ms(dev, period_ms);
}
C

2.3 Provide the user space wrapper with the prefix __syscall before the API function declaration.

Definition

In this exercise, we are implementing the driver to support system calls. This means the driver’s API can be invoked from supervisor mode and user mode with elevation steps. You can find more details in System Calls.

Copy
__syscall int blink_set_period_ms(const struct device *dev,
				  unsigned int period_ms);
C

2.4 Define a helper function blink_off() to turn off the blinking.

In this case, it will use a previously defined function with the prefix, so we don’t need any additional prefixes in this one. This is a static inline function using the driver`s API with preconfigured settings. We can introduce them to provide the user with the possibility to execute the most common driver actions without implementing them every time in the application.

Copy
static inline int blink_off(const struct device *dev)
{
	return blink_set_period_ms(dev, 0);
}
C

2.5 Add the syscall header at the end of the header file.

Any header file that declares system calls must include a special generated header at the very bottom of the header file. This header follows the naming convention syscalls/<name of header file>, as described in System Calls

Copy
#include <syscalls/blink.h>
C

2.6 Let the build system know where to find the syscalls declaration.

Add our driver class header to the syscalls list by modifying CMakeLists.txt in the root of the custom driver module:

Copy
zephyr_syscall_include_directories(include)
CMake

3. Implement the gpio_led driver to belong to the custom driver class blink.

Now that we have defined the custom driver class: blink. We want our device driver to implement the API of the class. This will be implemented in the file gpio_led.c found in custom_driver_module/drivers/blink.

3.1 Firstly, we create the driver’s data structure.

The LED blinking action will be performed in the timer’s callback.

Copy
struct blink_gpio_led_data {
	struct k_timer timer;
};
C

3.2 Next, define the configuration structure for the driver in drivers/blink/gpio_led.c

Copy
struct blink_gpio_led_config {
	struct gpio_dt_spec led;
	unsigned int period_ms;
};
C

3.3 Assign the blink_gpio_led_set_period_ms function as the driver API function.

The driver functions are already prepared for this exercise, so we only need to configure our API structures to use them properly. This time, we will use the DEVICE_API(class, function) macro, which assigns a selected function to a particular device driver class.

In our case, we create a structure instance of the blink (subsystem) class and connect the blink_gpio_led_set_period_ms function to .set_period_ms as part of the driver API.

Copy
static DEVICE_API(blink, blink_gpio_led_api) = {
	.set_period_ms = &blink_gpio_led_set_period_ms,
};
C

4. Define the device.

Now, it is time to define our custom device. We will assign API and configuration structures to the proper fields in the device definition structure.

4.1 Create the data structure instance template.

Put the following code in the BLINK_GPIO_LED_DEFINE macro

Copy
static struct blink_gpio_led_data data##inst;                          \
C

4.2 Create the configuration structure instance template.

In step 1, we created a binding containing the fields led_gpios and blink_period_ms. Now, we can use these fields to get configuration parameters from the devicetree.

  • As led parameter is of type gpio_dt_spec we expect to have the corresponding property (led-gpios) in the devicetree node. The macro GPIO_DT_SPEC_INST_GET() will parse and convert the parameter for us.
  • For the period_ms parameter, we will search for a parameter with this name in the devicetree node using DT_INST_PROP_OR(). If nothing is found, it gets the value 0
Copy
	static const struct blink_gpio_led_config config##inst = {             \
	    .led = GPIO_DT_SPEC_INST_GET(inst, led_gpios),                     \
	    .period_ms = DT_INST_PROP_OR(inst, blink_period_ms, 0U),           \
	};                                                                     \
C

4.3 Declare the device definition template.

Copy
	DEVICE_DT_INST_DEFINE(inst, blink_gpio_led_init, NULL, &data##inst,    \
			      &config##inst, POST_KERNEL,                                  \
			      CONFIG_BLINK_INIT_PRIORITY,                                  \
			      &blink_gpio_led_api);
C

Notice that we are using the CONFIG_BLINK_INIT_PRIORITY for the device driver initialization priority this time. This is one of the driver’s configuration build parameters. We will define it as a Kconfig symbol in the next step.

When we complete adding these steps, the whole macro should look like:

Copy
#define BLINK_GPIO_LED_DEFINE(inst)                                         \
    /* STEP 4.1 Create data structure instance template*/                   \
    static struct blink_gpio_led_data data##inst;                           \
                                                                            \
    /* STEP 4.2 Create configuration structure instance template */         \
    static const struct blink_gpio_led_config config##inst = {              \
        .led = GPIO_DT_SPEC_INST_GET(inst, led_gpios),                      \
        .period_ms = DT_INST_PROP_OR(inst, blink_period_ms, 0U),            \
    };                                                                      \
                                                                            \
    /*STEP 4.3 Declare device definition template */                        \
    DEVICE_DT_INST_DEFINE(inst, blink_gpio_led_init, NULL, &data##inst,     \
                  &config##inst, POST_KERNEL,                               \
                  CONFIG_BLINK_INIT_PRIORITY,                               \
                  &blink_gpio_led_api);
C

4.4 Define the driver’s init priority.

Define the Kconfig BLINK_INIT_PRIORITY in drivers/blink/Kconfig.

Set the default value to KERNEL_INIT_PRIORITY_DEVICE.

Copy
config BLINK_INIT_PRIORITY
	int "Blink device drivers init priority"
	default KERNEL_INIT_PRIORITY_DEVICE
	help
	  Blink device drivers init priority.
Kconfig

5. Use the custom driver in the application.

To be able to use the driver in our application, we first need to add a node to the devicetree with the binding we defined earlier in the exercise.

5.1 Create a blink_gpio_leds device node in the devicetree.

Create an overlay file <board_target>.overlay in app/boards, with the name corresponding to the board you are using.

In the overlay file, define a blink_led node, and add the led-gpios and blink-period-ms parameters. For led-gpios you can use one of the LEDs populated in the board (pin 2.9 for the nRF54L15 DK). For blink-period-ms, set a blink period, for example 1 second (1000 ms).

Lastly, set the node compatibility to blink-gpio-led.

The overlay file should look like this

Copy
/ {
	blink_led: blink-led {
		compatible = "blink-gpio-led";
		led-gpios = <&gpio2 9 GPIO_ACTIVE_HIGH>;
		blink-period-ms = <1000>;
	};
};
Devicetree

5.2 Enable the blink driver in the application.

Enable the blink driver in the application by adding the following line to the prj.conf file

Copy
CONFIG_BLINK=y
Kconfig

5.3 Use the custom blink API from the driver to change the blinking period in the application.

Add the following code into main.c

Copy
   /* Use custom API  to turn LED  off */
     int ret = blink_off(blink);
     if (ret < 0) {
         LOG_ERR("Could not turn off LED (%d)", ret);
         return 0;
     }
 
     while (1) {
        
        /* When LED is constantly enabled - start over with high blinking period*/
        if (period_ms == 0U) {
            period_ms = BLINK_PERIOD_MS_MAX;
        } else {
            period_ms -= BLINK_PERIOD_MS_STEP;
        }
 
        printk("Setting LED period to %u ms\n",
            period_ms);
        
        /* Use custom API to change LED blinking period*/
        blink_set_period_ms(blink, period_ms);
       

        k_sleep(K_MSEC(2000));
     }
C

6. Build and flash the application to your board.

Important

To build the project properly, make sure to create a build configuration for the app directory, not the root of the exercise directory.

When building from the command line, the command should look like this: west build app -b <board>

Observe how the blinking period changes every 2 seconds.

Make sure to Log in or Register to save your progress

Back
Next

Nordic Developer Academy Privacy Policy

 

1. Introduction 

In this Privacy Policy you will find information on Nordic Semiconductor ASA (“Nordic Semiconductor”) processes your personal data when you use the Nordic Developer Academy.

References to “we” and “us” in this document refers to Nordic Semiconductor.

 

2. Our processing of personal data when you use the Nordic Developer Academy 

2.1 Nordic Developer Academy 

Nordic Semiconductor processes personal data in order to provide you with the features and functionality of the Nordic Developer Academy. Creating a user account is optional, but required if you want to track you progress and view your completed courses and obtained certificates. If you choose to create a user account, we will process the following categories of personal data:

  • Email
  • Name
  • Password (encrypted)
  • Course progression (e.g. which course you have completely or partly completed)
  • Certificate information, which consists of name of completed course and the validity of the certificate
  • Course results

During your use of the Nordic Developer Academy, you may also be asked if you want to provide feedback. If you choose to respond to any such surveys, we will also process the personal data in your responses in that survey.

The legal basis for this processing is GDPR article 6 (1) b. The processing is necessary for Nordic Semiconductor to provide the Nordic Developer Academy under the Terms of Service.

 

2.2 Analytics 

If you consent to analytics, Nordic Semiconductor will use Google Analytics to obtain statistics about how the Nordic Developer Academy is used. This includes collecting information on for example what pages are viewed, the duration of the visit, the way in which the pages are maneuvered, what links are clicked, technical information about your equipment. The information is used to learn how Nordic Developer Academy is used and how the user experience can be further developed.

 

2.2 Newsletter 

You can consent to receive newsletters from Nordic from within the Nordic Developer Academy. How your personal data is processed when you sign up for our newsletters is described in the Nordic Semiconductor Privacy Policy.

 

3. Retention period 

We will store your personal data for as long you use the Nordic Developer Academy. If our systems register that you have not used your account for 36 months, your account will be deleted.

 

4. Additional information 

Additional information on how we process personal data can be found in the Nordic Semiconductor Privacy Policy and Cookie Policy.

‍‍ 

Nordic Developer Academy Terms of Service

 

1. Introduction

‍These terms and conditions (“Terms of Use”) apply to the use of the Nordic Developer Academy, provided by Nordic Semiconductor ASA, org. nr. 966 011 726, a public limited liability company registered in Norway (“Nordic Semiconductor”). ‍

Nordic Developer Academy allows the user to take technical courses related to Nordic Semiconductor products, software and services, and obtain a certificate certifying completion of these courses. By completing the registration process for the Nordic Developer Academy, you are agreeing to be bound by these Terms of Use.

These Terms of Use are applicable as long as you have a user account giving you access to Nordic Developer Academy.‍

‍2. Access to and use of Nordic Developer Academy

‍‍Upon acceptance of these Terms of Use you are granted a non-exclusive right of access to, and use of Nordic Developer Academy, as it is provided to you at any time. Nordic Semiconductor provides Nordic Developer Academy to you free of charge, subject to the provisions of these Terms of Use and the Nordic Developer Academy Privacy Policy.

To access select features of Nordic Developer Academy, you need to create a user account. You are solely responsible for the security associated with your user account, including always keeping your login details safe.

You will able to receive an electronic certificate from Nordic Developer Academy upon completion of courses. By issuing you such a certificate, Nordic Semiconductor certifies that you have completed the applicable course, but does not provide any further warrants or endorsements for any particular skills or professional qualifications.

Nordic Semiconductor will continuously develop Nordic Developer Academy with new features and functionality, but reserves the right to remove or alter any existing functions without notice.

‍3. Acceptable use

You undertake that you will use Nordic Developer Academy in accordance with applicable law and regulations, and in accordance with these Terms of Use.‍ You must not modify, adapt, or hack Nordic Developer Academy or modify another website so as to falsely imply that it is associated with Nordic Developer Academy, Nordic Semiconductor, or any other Nordic Semiconductor product, software or service.

You agree not to reproduce, duplicate, copy, sell, resell or in any other way exploit any portion of Nordic Developer Academy, use of Nordic Developer Academy, or access to Nordic Developer Academy without the express written permission by Nordic Semiconductor. You must not upload, post, host, or transmit unsolicited email, SMS, or \”spam\” messages.

You are responsible for ensuring that the information you post and the content you share does not;

  • contain false, misleading or otherwise erroneous information
  • infringe someone else’s copyrights or other intellectual property rights
  • contain sensitive personal data or
  • contain information that might be received as offensive or insulting.
  • Such information may be removed without prior notice.

‍Nordic Semiconductor reserves the right to at any time determine whether a use of Nordic Developer Academy is in violation of its requirements for acceptable use.

Violation of the at any time applicable requirements for acceptable use may result in termination of your account. We will take reasonable steps to notify you and state the reason for termination in such cases.

‍4. Routines for planned maintenance

‍Certain types of maintenance may imply a stop or reduction in availability of Nordic Developer Academy. Nordic Semiconductor does not warrant any level of service availability but will provide its best effort to limit the impact of any planned maintenance on the availability of Nordic Developer Academy.

5. Intellectual property rights

‍Nordic Semiconductor retains all rights to all elements of Nordic Developer Academy. This includes, but is not limited to, the concept, design, trademarks, know-how, trade secrets, copyrights and all other intellectual property rights.

Nordic Semiconductor receives all rights to all content uploaded or created in Nordic Developer Academy. You do not receive any license or usage rights to Nordic Developer Academy beyond what is explicitly stated in this Agreement.

‍6. Liability and damages

‍Nothing within these Terms of Use is intended to limit your statutory data privacy rights as a data subject, as described in the Nordic Developer Academy Privacy Policy. ‍You acknowledge that errors might occur from time to time and waive any right to claim for compensation as a result of errors in Nordic Developer Academy. When an error occurs, you shall notify Nordic Semiconductor of the error and provide a description of the error situation.

You agree to indemnify Nordic Semiconductor for any loss, including indirect loss, arising out of or in connection with your use of Nordic Developer Academy or violations of these Terms of Use. ‍Nordic Semiconductor shall not be held liable for, and does not warrant that (i) Nordic Developer Academy will meet your specific requirements, (ii) Nordic Developer Academy will be uninterrupted, timely, secure, or error-free, (iii) the results that may be obtained from the use of Nordic Developer Academy will be accurate or reliable, (iv) the quality of any products, services, information, or other material purchased or obtained by you through Nordic Developer Academy will meet your expectations, or that (v) any errors in Nordic Developer Academy will be corrected.

You accept that this is a service provided to you without any payment and hence you accept that Nordic Semiconductor will not be held responsible, or liable, for any breaches of these Terms of Use or any loss connected to your use of Nordic Developer Academy. Unless otherwise follows from mandatory law, Nordic Semiconductor will not accept any such responsibility or liability.

‍7. Change of terms

‍Nordic Semiconductor may update and change the Terms of Use from time to time. Nordic Semiconductor will seek to notify you about significant changes before such changes come into force and give you a possibility to evaluate the effects of proposed changes. Continued use of Nordic Developer Academy after any such changes shall constitute your acceptance of such changes. You can review the current version of the Terms of Use at any time at https://academy.nordicsemi.com/terms-of-service/

‍8. Transfer of rights

‍Nordic Semiconductor is entitled to transfer its rights and obligation pursuant to these Terms of Use to a third party as part of a merger or acquisition process, or as a result of other organizational changes.

‍9. Third Party Services

‍‍To the extent Nordic Developer Academy facilitates access to services provided by a third party, you agree to comply with the terms governing such third party services. Nordic Semiconductor shall not be held liable for any errors, omissions, inaccuracies, etc. related to such third party services.

‍10. Dispute resolution

‍‍The Terms of Use and any other legally binding agreement between yourself and Nordic Semiconductor shall be subject to Norwegian law and Norwegian courts’ exclusive jurisdiction.

 

Switch language?

Progress is tracked separately for each language. Switching will continue from your progress in that language or start fresh if you haven't begun.

Your current progress is saved, and you can switch back anytime.

Log in
Don’t have an account? Register an account

Forgot your password?
Register an account
Already have an account? Log in
(All fields are required unless specified optional)

  • 8 or more characters
  • Upper and lower case letters
  • At least one number or special character

Forgot your password?
Enter the email associated with your account, and we will send you a link to reset your password.

Back to Log in

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.

      Change summary

      What's new in the latest version

      General updates

      General updates

      •Support for nRF54LS05 DK (Available through the early access sampling program)
      •Support for the nRF54LM20B with Axon NPU for Edge AI applications
      Bluetooth LE updates

      Bluetooth LE updates

      •Quality of Service module is now production-ready.
      •New experimental features for RF testing (Direct Test Mode) and low-latency packet handling (LE Flushable ACL).
      MCUboot & Partition Manager

      MCUboot & Partition Manager

      •Single-Slot DFU and RAM Load mode are both promoted to fully supported
      •Partition Manager is officially deprecated in favor of Zephyr's devicetree-based partitioning.