Feedback
Feedback

If you are having issues with the exercises, please create a ticket on DevZone: devzone.nordicsemi.com
Click or drag files to this area to upload. You can upload up to 2 files.

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:

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.

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.

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.

  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.

__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 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
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.

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

2.4 Define an API 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.

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

#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:

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.

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

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 class blink (subsystem) and connect the blink_gpio_led_set_period_ms function to .set_period_ms as part of the driver API.

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

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
	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.

	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.

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.

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 combability to blink-gpio-led.

The overlay file should look like this

/ {
	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

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

   /* 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.

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.