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 the custom driver module, 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:
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.
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.
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: intdescription: 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. * * @paramdev Blink device instance. * @paramperiod_ms Period of the LED blink in milliseconds, 0 to * disable blinking. * * @retval 0 if successful. * @retval -EINVAL if @pperiod_ms can not be set. * @retval -errno Other negative errno code on failure. */int (*set_period_ms)(conststruct device *dev, unsignedint 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 which belongs to this class. Although they have the same API function, the behavior will be specific to a particular drivers’ 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
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.
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 classblink.
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.
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 class blink (subsystem) and connect the blink_gpio_led_set_period_ms function to .set_period_ms as part of the driver API.
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
staticstruct 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_gpiosand 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
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.
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.
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 combability to blink-gpio-led.
Enable the blinkdriver 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);return0; }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.
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.