Zephyr Port Devices Driver



Introduction

Zephyr Port Devices driver

I worked for almost two decades in the software industry. In the early 2000s, I was developing applications on Windows, Linux, and various flavours of Unix. On the Windows side, we had Microsoft Visual Studio, MFC, NMake, and CL. On the Linux/Unix side, we had GCC, POSIX and various types of windowing toolkits (X-Window + Motif, anyone?). Cross platform development was a challenge, but even before the advent of fancy tools like Qt and wxWindows, we were able to structure the code so that large parts of it was compatible across the different operating systems.

Install the OPOS drivers as per the device manufacturers installation instructions. Magnetic Stripe Reader Windows provides support for the following magnetic stripe readers from Magtek and IDTech based on their Vendor ID and Product ID (VID/PID). Such a driver could be added later on if need arises. Next step: This change is proposing an origin point for transition from 'c' to device tree configuration. For now, it is used on 1 driver and 2 boards. It will then have to be extended on 2 axis (boards, drivers) to cover the whole stm32 plan. Virtual COM port (VCP) drivers cause the USB device to appear as an additional COM port available to the PC. Application software can access the USB device in the This page contains the VCP drivers currently available for FTDI devices. For D2XX Direct drivers, please click here.

Compared to that, cross-platform development in the embedded world today is far more difficult. First of all, there are many chip architectures – AVR, ARM, Xtensa, RISC-V, etc., and these chips vary hugely in their capabilities and supported peripherals. Then there are different sorts of toolchains, libraries, and development environments. Not all them can run an OS (or an RTOS) and in many cases, people don’t prefer to. Overall, good luck trying to port your code from once device to another! Although efforts like mbed try to address the cross-platform issue, they are restricted to certain chip families.

Why not just use embedded Linux then? You certainly can in many cases, as the huge success of Raspberry Pi shows. But when it comes to resource constrained low power systems, Linux is just too heavy. Enter Zephyr – an RTOS (Real Time Operating System) that is very much influenced by Linux, but designed specifically with the above constraints in mind.

Objective

In this project, we will build a BLE (Bluetooth Low Energy) device that broadcasts data from a BME280 temperature/humidity sensor. For this, we will use the Zephyr RTOS on the Electronut Labs hackaBLE board based on the Nordic nRF52832 SoC. For programming hackaBLE, we will use the Electronut Labs Bumpy SWD debugger based on the blackmagicprobe project.

Getting Started

The first thing to do of course, is to install Zephyr. For this task and for all tasks ahead, the official documentation page is your best reference. You can install Zephyr on Linux, Mac, or Windows. But I did it on Linux, and hence this article will reflect that experience. As you go through the official installation procedure, I recommend that you install the Zephyr SDK as well, since it has the required toolchain. Makes it easy to get started.

Now, before we proceed to build our “hello world” application with Zephyr, let’s look at a few concepts that are central to working with this RTOS.

CMake

If you have worked with embedded systems for any considerable time, you’re probably familiar with Makefiles. Well, CMake is a system that makes Makefiles. CMake is a cross-platform tool that uses configuration files to create build files specific to your system. Zephyr uses CMake, and building a project goes something like this:

Ninja is a build system designed to use with CMake. Apparently it’s faster – as ninjas tend to be. In addition to CMake/Ninja, Zephyr is also working on a “meta-tool” called west which will replace the above eventually. But for now you can still use our masked friend.

Device Trees

Your embedded device has a complex hierarchy of components, starting from higher level elements like LEDs and Buttons, down to SoC peripherals like I2C and ADC. In Linux, and in Zephyr, this hierarchy is represented as a device tree. The device tree resides in DTS (Device Tree Source) files – these are human readable text files. In Linux, these are compiled into binary DTB (Device Tree Blob) files using a DTC (Device Tree Compiler). In Zephyr, to reduce overhead, the DTS information is just used during compile time. The DTS files are naturally hierarchical. For example the nrf52840_pca10056.dts includes nrf52840_qiaa.dtsi, which in turn includes nrf52840.dtsi – going from board to chip variant to the core SoC.

If you are not familiar with device trees, the whole thing might seem a bit odd. But consider this: how does the Linux kernel support such a huge variety of third party devices without having to recompile the code every time? Because the device information can be passed into the kernel as a binary “blob” – the DTB.

So how do you get Zephyr to talk to your particular device? Chances are that a variant of this device is already supported by the kernel. So you take the relevant DTS and either make a modified copy of it, or write an overlay for it – something that adds or modifies the existing device so it matches yours. The DTS file along with some other configuration files constitute the “board files” for your device. We’ll be creating these files for hackaBLE in this project, so things will become clearer further ahead.

Config Files

Device Trees help you describe the hardware. There is another level of application-specific customisation required, which will let you enable only those features you really need. In Zephyr, this is done via the Kconfig configuration system. The “board files” we talked about earlier contain some default configurations, which can be further refined using application specific configurations. For example, if you want to enable the Bluetooth subsystem, you would have this in your project’s prj.conf file:

Enabling only what you need is critical for embedded systems, since it has a direct impact on things like power consumption, memory, and performance.

Kconfig also provides an interactive UI for setting all the configuration options. Doing a ninja menuconfig in the build directory with bring up this UI:

[Image source: https://docs.zephyrproject.org/latest/application/index.html]

menuconfig gives you the entire configuration tree. You can search and navigate through this tree to set your relevant options. It’s a clunky interface, but it’s lightweight, and works across platforms. Once you set your options, save, and quit, you can rebuild your application with the new options. But here’s the catch – these options are saved inside your build directory, and will be blown away if you delete this directory. So to save these options for the future, you need copy these to your prj.conf file. (Here’s a menuconfig tip – while you are on a configuration option, press Shift-?, and you will get a help file that gives you the exact name of that option.)

Now let’s put this above knowledge to some use by building a couple of Zephyr applications on hackaBLE.

Required Hardware

You need the following hardware to build this project.

  1. Electronut Labs hackaBLE
  2. Electronut Labs Bumpy SWD programmer
  3. BME280 breakout board
  4. Breadboard, connecting wires

Hello World on hackaBLE

The hackaBLE board is not directly supported by Zephyr, so the first thing we want to do is create the required board files. hackaBLE uses the Nordic nRF52832 SoC, so we’ll just modify the board files for the Nordic nRF52832-DK board which is already supported by Zephyr, and listed under nrf52_pca10040.

Adding hackaBLE to Zephyr

First, we need to copy boards/arm/nrf52_pca10040/ to a new directory boards/arm/nrf52_hackable/. Then we rename the files as follows:

The next step is to replace the occurrences of pca10040 inside the above files with hackable. The next important edit is for board.cmake which will contain just:

This is required for us to program hackaBLE using the Bumpy SWD debugger, which is based on blackmagicprobe. Next, we’ll edit the DTS file to map the correct pins to the peripherals we will be using.

We need to use I2C and UART in this project, so we’ve correspondingly mapped the nRF52832 SoC peripherals to convenient pin numbers on hackaBLE.

Code Setup

The Zephyr build system allows you to easily build your project outside the installation folder. It’s usually easiest to just copy a sample project over and then modify the configuration. In our case, the folder looks like this:

Here’s what our prj.conf looks like:

Remember our discussion on Kconfig? The above file tells CMake that we want to enable GPIOs and the UART console.

Our main.c is very simple:

Let’s go through the above code quickly. The first thing it does is to get the GPIO_0 device binding – again, this come from the DTS file, and nRF52832 has only one GPIO port – P0. We then configure P0.17 – the LED red channel – as an output. In the main loop, all we do is flash the LED and print “hello world”, with delays in between. The printk outputs to the serial port, as per our config file which has enabled UART console – CONFIG_UART_CONSOLE=y.

Now we go into the build directory and build our project as follows:

Before we upload the code, let’s take a look at the hardware hookup.

Hardware Connections

For this project, hook up the hardware as follows so it matches up with our DTS and config files.

hackaBLEBumpyBME280
P0.27Rx
P0.25Tx
P0.03SCL
P0.04SDA
GNDGNDGND
VDD3V3VDD

Upload and Test

The last step is to flash the code:

Port

To test the output, we open a serial terminal using picocom:

In the attached screenshot below, you can see the output:

From the above, you also get an idea of my workflow. I use the byobu terminal multiplexer, and the four screens from top left, going anti-clockwise are – zephyr build, USB monitoring using dmesg -w, picocom output, and a Python shell for calculations.

Zephyr Port Devices Driver

Now that we’ve got “hello” going. let’s try something more interesting.

Building a BLE Temperature/Humidity Monitor

In this project, we’re going to enable the Zephyr BLE stack, communicate with the BME280 sensor using I2C, and then send the temperature and humidity data in two ways – via BLE advertisement packets, as well as via GATT characteristics – once a connection is made by a BLE central device like a mobile phone.

Configuring BLE and BME280

To enable BLE, you need the following in your prj.conf:

Oh, I didn’t come up with all the above stuff by myself. Zephy has fine BLE examples that I pilfered from. The above enables BLE and sets up various parameters – for example, CONFIG_BT_PERIPHERAL=y says that our device is a peripheral, not a central, and CONFIG_BT_DEVICE_NAME=”hackaBLE” sets the name we advertise by.

Next we need to configure the BME280 sensor, which, luckily is already supported by Zephyr:

Above, we first configure I2C, and there are some special settings for NRF which you can see above. Once I2C is enabled, we then enable the sensor subsystem on Zephyr, and more specifically, the BME280 sensor.

The Code

I won’t go through the whole code here, but here are the highlights.

We start by defining the main BLE service and the two characteristics we will be using – Temperature and Humidity:

These are added to the BLE subsystem as follows:

In the code above, you can see read/write functions assigned to each characteristic, as well as permissions, and the Client Characteristic Configuration Descriptor (CCCD) which lets the client (the central) enable notifications.

Here’s how we set up the BLE advertisement packet.

Above, we’ll use the third and fourth bytes in mfg_data to send the most significant digits of temperature and humidity respectively.

We access the sensor in a manner similar to what we did with GPIO before:

Here’s how you get the BME280 data:

Zephyr Port Devices Drivers

In Zephyr, sensor data is stored in a struct as follows:

So in our code, we retrieve the temperature and humidity, and store them both for advertisement packets and for the characteristics.

Here’s our main loop:

What we’re doing above is notifying the connected device with the new sensor values as well as updating the advertising data.

Build and Test

You can build and flash the code similar to the hello example. To test the device, we will be using the Nordic nRFConnect mobile app. Here’s what you see when you scan:

In the above screenshot, you can see that the last two bytes of the advertisement packet manufacturer data is 0x1b21 – 27 degree C with a humidity of 33%.

Now, let’s connect to it.

You can see the UUID of the primary service we defined. If you click on it, you will see the characteristics:

Taking some help from Python, we get:

Hence, T = 27.900000 deg C, H = 34.182617 %. If you enable notifications, you will see that these values update on the phone every two seconds, as per our code.

So here we are – a BLE device based on Nordic nRF52832 that transmits weather data, powered by the Zephyr RTOS!

Programming hackaBLE without Bumpy

It’s perfectly possible to program hackaBLE without Bumpy. If you want to use the Nordic nRF52832-DK (PCA10040) for that purpose, you need to use the same board.cmake as the PCA10040 in the board files. You’ll also need to match the Rx/Tx lines of hackaBLE and the DK in the DTS file to get the serial output.

Conclusion

I learned a lot of programming on Linux. I always liked the “everything is a file” idea and standard programming concepts that worked across systems. Thinking in terms of processes, threads, inter-process communication mechanisms, sockets, etc. was natural, and these were concepts and programming conventions that were portable. But working with embedded systems today, vendor lock-in is a worrying trend, whether it be proprietary hardware programmers, expensive development tools, non portable APIs, or closed protocol stacks. There is a dire need for open, vendor-neutral frameworks like Zephyr, and the fact it follows the Linux model is a big plus in my view. We are definitely looking at Zephyr as the primary platform for our upcoming projects and products.

Downloads

You can download the source code for this article at the link below:

Acknowledgements

I thank Tavish Naruka for introducing me to Zephyr, as well as troubleshooting issues on various occasions.

The USB device stack is split into three layers:
  • USB device controller drivers (hardware dependent)
  • USB device core layer (hardware independent)
  • USB device class drivers (hardware independent)

USB Vendor and Product identifiers¶

The USB Vendor ID for the Zephyr project is 0x2FE3. The default USB ProductID for the Zephyr project is 0x100. The USB bcdDevice Device Release Numberrepresents the Zephyr kernel major and minor versions as a binary codeddecimal value. When a vendor integrates the Zephyr USB subsystem into aproduct, the vendor must use the USB Vendor and Product ID assigned to them.A vendor integrating the Zephyr USB subsystem in a product must not use theVendor ID of the Zephyr project.

The USB maintainer, if one is assigned, or otherwise the Zephyr TechnicalSteering Committee, may allocate other USB Product IDs based on well-motivatedand documented requests.

USB device controller drivers¶

The Device Controller Driver Layer implements the low level control routinesto deal directly with the hardware. All device controller drivers shouldimplement the APIs described in file usb_dc.h. This allows the integration ofnew USB device controllers to be done without changing the upper layers.For now only Quark SE USB device controller (Designware IP) is supported.

Structures¶

Structure containing the USB endpoint configuration.
  • ep_addr: endpoint address, the number associated with the EP in the deviceconfiguration structure.IN EP = 0x80 | <endpoint number>. OUT EP = 0x00 | <endpoint number>
  • ep_mps: Endpoint max packet size.
  • ep_type: Endpoint type, may be Bulk, Interrupt or Control. Isochronousendpoints are not supported for now.
Status codes reported by the registered device status callback.
  • USB_DC_ERROR: USB error reported by the controller.
  • USB_DC_RESET: USB reset.
  • USB_DC_CONNECTED: USB connection established - hardware enumeration is completed.
  • USB_DC_CONFIGURED: USB configuration done.
  • USB_DC_DISCONNECTED: USB connection lost.
  • USB_DC_SUSPEND: USB connection suspended by the HOST.
  • USB_DC_RESUME: USB connection resumed by the HOST.
  • USB_DC_INTERFACE: USB Interface selected by the HOST.
  • USB_DC_UNKNOWN: Initial USB connection status.
Status Codes reported by the registered endpoint callback.
  • USB_DC_EP_SETUP: SETUP packet received.
  • USB_DC_EP_DATA_OUT: Out transaction on this endpoint. Data is availablefor read.
  • USB_DC_EP_DATA_IN: In transaction done on this endpoint.

APIs¶

The following APIs are provided by the device controller driver:

usb_dc_attach()
This function attaches USB for device connection. Upon success, the USB PLLis enabled, and the USB device is now capable of transmitting and receivingon the USB bus and of generating interrupts.
usb_dc_detach()
This function detaches the USB device. Upon success the USB hardware PLL ispowered down and USB communication is disabled.
usb_dc_reset()
This function returns the USB device to it’s initial state.
usb_dc_set_address()
This function sets USB device address.
usb_dc_set_status_callback()
This function sets USB device controller status callback. The registeredcallback is used to report changes in the status of the device controller.The status code are described by the usb_dc_status_code enumeration.
usb_dc_ep_configure()
This function configures an endpoint. usb_dc_ep_cfg_data structure providesthe endpoint configuration parameters: endpoint address, endpoint maximumpacket size and endpoint type.
usb_dc_ep_set_stall()
This function sets stall condition for the selected endpoint.
usb_dc_ep_clear_stall()
This functions clears stall condition for the selected endpoint
usb_dc_ep_is_stalled()
This function check if selected endpoint is stalled.
usb_dc_ep_halt()
This function halts the selected endpoint
usb_dc_ep_enable()
This function enables the selected endpoint. Upon success interrupts areenabled for the corresponding endpoint and the endpoint is ready fortransmitting/receiving data.
usb_dc_ep_disable()
This function disables the selected endpoint. Upon success interrupts aredisabled for the corresponding endpoint and the endpoint is no longer ablefor transmitting/receiving data.
usb_dc_ep_flush()
This function flushes the FIFOs for the selected endpoint.
usb_dc_ep_write()
This function writes data to the specified endpoint. The suppliedusb_ep_callback function will be called when data is transmitted out.
usb_dc_ep_read()
This function is called by the Endpoint handler function, after an OUTinterrupt has been received for that EP. The application must only call thisfunction through the supplied usb_ep_callback function.
usb_dc_ep_set_callback()
This function sets callback function for notification of data receivedand available to application or transmit done on the selected endpoint.The callback status code is described by usb_dc_ep_cb_status_code.
usb_dc_ep_read_wait()
This function is similar to usb_dc_ep_read, the difference being that, itdoesn’t clear the endpoint NAKs so that the consumer is not bogged down byfurther upcalls till he is done with the processing of the data. The callershould reactivate ep by invoking usb_dc_ep_read_continue() do so.
usb_dc_ep_read_continue()
Clear the endpoint NAK and enable the endpoint to accept more data from thehost. Usually called after usb_dc_ep_read_wait() when the consumer is fineto accept more data. Thus these calls together acts as flow controlmechanism.
usb_dc_ep_mps()
Get endpoint max packet size.

USB device core layer¶

The USB Device core layer is a hardware independent interface between USBdevice controller driver and USB device class drivers or customer applications.It’s a port of the LPCUSB device stack. It provides the followingfunctionalities:

  • Responds to standard device requests and returns standard descriptors,essentially handling ‘Chapter 9’ processing, specifically the standarddevice requests in table 9-3 from the universal serial bus specificationrevision 2.0.
  • Provides a programming interface to be used by USB device classes orcustomer applications. The APIs are described in the usb_device.h file.
  • Uses the APIs provided by the device controller drivers to interact withthe USB device controller.

Structures¶

Callback function signature for the device status.

Callback function signature for the USB Endpoint.

Callback function signature for class specific requests. For host to devicedirection the ‘len’ and ‘payload_data’ contain the length of the received dataand the pointer to the received data respectively. For device to host classrequests, ‘len’ and ‘payload_data’ should be set by the callback functionwith the length and the address of the data to be transmitted bufferrespectively.

This structure contains configuration for a certain endpoint.
  • ep_cb: callback function for notification of data received and availableto application or transmit done, NULL if callback not required byapplication code.
  • ep_addr: endpoint address. The number associated with the EP in the deviceconfiguration structure.
This structure contains USB interface configuration.
  • class_handler: handler for USB Class specific Control (EP 0)communications.
  • custom_handler: the custom request handler gets a firstchance at handling the request before it is handed over to the‘chapter 9’ request handler.
  • payload_data: this data area, allocated by the application, is used tostore class specific command data and must be large enough to store thelargest payload associated with the largest supported Class’ command set.
This structure contains USB device configuration.
  • usb_device_description: USB device description, seehttp://www.beyondlogic.org/usbnutshell/usb5.shtml#DeviceDescriptors
  • cb_usb_status: callback to be notified on USB connection status change
  • interface: USB class handlers and storage space.
  • num_endpoints: number of individual endpoints in the device configuration
  • endpoint: pointer to an array of endpoint configuration structures(usb_cfg_data) of length equal to the number of EP associated with thedevice description, not including control endpoints.

The class drivers instantiates this with given parameters using the“usb_set_config” function.

APIs¶

usb_set_config()
This function configures USB device.
usb_deconfig()
This function returns the USB device back to it’s initial state
usb_enable()
This function enable USB for host/device connection. Upon success, the USBmodule is no longer clock gated in hardware, it is now capable oftransmitting and receiving on the USB bus and of generating interrupts.
usb_disable()
This function disables the USB device. Upon success, the USB module clockis gated in hardware and it is no longer capable of generating interrupts.
usb_write()
write data to the specified endpoint. The supplied usb_ep_callback will becalled when transmission is done.
usb_read()
This function is called by the endpoint handler function after an OUTinterrupt has been received for that EP. The application must only callthis function through the supplied usb_ep_callback function.
usb_transfer()
This asynchronous function starts a usb transfer from/to a specified buffer.A callback can be provided and will be called on transfer completion.This function can be used in IRQ context.
usb_transfer_sync()
This function is the synchronous version of the usb_transfer function,waiting for transfer completion before returning.

USB device class drivers¶

To initialize the device class driver instance the USB device class drivershould call usb_set_config() passing as parameter the instance’s configurationstructure.

Zephyr Port Devices Driver License Test

Zephyr Port Devices Driver

For example, for CDC_ACM sample application:

To enable the USB device for host/device connection:

The class device requests are forwarded by the USB stack core driver to theclass driver through the registered class handler.For the CDC ACM sample class driver, ‘cdc_acm_class_handle_req’ processesthe SET_LINE_CODING, CDC_SET_CONTROL_LINE_STATE and CDC_GET_LINE_CODINGclass requests:

The class driver should wait for the USB_DC_INTERFACE device status codebefore transmitting any data.

There are two ways to transmit data, using the ‘low’ level read/write API orthe ‘high’ level transfer API.

Zephyr Port Devices Driver Device

low level API:

To transmit data to the host, the class driver should call usb_write().Upon completion the registered endpoint callback will be called. Beforesending another packet the class driver should wait for the completion ofthe previous write. When data is received, the registered endpoint callbackis called. usb_read() should be used for retrieving the received data.For CDC ACM sample driver this happens via the OUT bulk endpoint handler(cdc_acm_bulk_out) mentioned in the endpoint array (cdc_acm_ep_data).

high level API:

Zephyr Port Devices Driver Updater

The usb_transfer method can be used to transfer data to/from the host. Thetransfer API will automatically split the data transmission into one or moreUSB transaction(s), depending endpoint max packet size. The class driver doesnot have to implement endpoint callback and should set this callback to thegeneric usb_transfer_ep_callback.