Using static libraries on a Zephyr RTOS Project

Zephyr RTOS uses the CMake tools to compile and build it’s projects. Also all provided modules use CMake files or are modified to work with CMake files so that they integrate with the Zephyr RTOS.

On it’s own, CMake is a massive tool and takes some time to hold all the concepts, and so to do a simple thing like adding a third-party static library to a Zephyr RTOS project can be a complicated task when not all sides of CMake tool are understood…

Anyway, a quick tip, for those, that like me, wanted to add static libraries to a Zephyr RTOS project:

Basically at the Zephyr project root directory there is a CMakeLists.txt file. To add our libraries we must modify this file. For example a standard Zephyr CMakeLists.txt file may look like:

# SPDX-License-Identifier: Apache-2.0

cmake_minimum_required(VERSION 3.13.1)

target_sources(app PRIVATE src/main.c)

Let’s say now that we want to link our project with a third party library provided in a static library format: OtherLib.a.

At the root of the project we might, or should, create a directory called, for example, lib, and copy our lib, our libs files to that directory. And then modify the CMakeLists.txt file to look like:

# SPDX-License-Identifier: Apache-2.0

cmake_minimum_required(VERSION 3.13.1)



FILE(GLOB app_sources src/*.c)
target_sources(app PRIVATE ${app_sources})

add_library(other3party_lib STATIC IMPORTED GLOBAL)

set_target_properties(other3party_lib PROPERTIES IMPORTED_LOCATION ${LIB_DIR}/OtherLib.a)

target_link_libraries(app PUBLIC other3party_lib)

Excluding the line FILE(GLOB app_sources src/*.c) that is used to add all C files on the src directory to the project, the other bold lines, specifically the last but one, are used to add the static library to the project.

If multiple libraries are needed to link, the set_target_properties line should be duplicated and modified to point to each library that is needed to link to the project.

And that’s it.

A Zephyr RTOS based TTN Lorawan node

My previous post about Zephyr RTOS sample project with the STM32 blue pill board and the LMIC related posts such as Setting the SPI interface for Lorawan TTN LMIC and Some quick notes about Lorawan LMIC Library where the necessary stepping stones to enable the prototype creation for a TTN (The Things Network) Lorawan node but this time using the Zephyr RTOS and the LoraMac Lorawan library for the network connection.

Specifically for the LoraMac Lorawan node library, a Zephyr RTOS LoraMac code port exists, so it provides a device driver/API to the Zephyr applications which enables them to have Lora/Lorawan connectivity.

The Arduino framework and LMIC library was used as a comparative solution while debugging and testing the settings and connections for a successful connection from the node to the TTN network, to make sure that all configuration was correct and the radio (a RFM95W module) was functional. So during testing I went back and forth between the two libraries: LMIC using the Arduino framework and LoraMac-Node with Zephyr RTOS during testing.

The boards used for testing where the STM32F103CB BluePill board, the STM32F407VE board and the Blackpill STM32F411CE board. All boards can be used with either the Arduino framework and the Zephyr RTOS but I settled on doing most of all the tests with the Blackpill F411 board.

This choice was made because the main issue with the BluePill is that it doesn’t have enough flash space to have the Zephyr RTOS, the USB driver for console logging through USB and the LoraMac-node code and sample program to be stored. Using LMIC and Arduino framework on Bluepill is possible and leaves some space, but with Zephyr RTOS it is only possible to do anything useful but without USB support for serial logging. Still just note that modifying the Zephyr project configuration to have the USB driver from removed, and therefore no console logging through USB, allows to flash the board, but at the end not too much space is left do anything useful with this board. So at the end I stopping doing any tests with the Bluepull and not used it further.

Both the two other boards, the F407 and F411, have more than enough space to do any testing, but the smaller form factor of the F411Blackpill  is ideal size to do the tests (it is breadboard friendly), so I ended up using the F411 for all tests, which means that all the following steps are for this board, but can be easily replicated to other boards as long there is enough flash space.

Zephyr RTOS and Lorawan support:

The Lorawan Zephyr RTOS support was out more or less in October 2020, and for a single board 96b-wistrios board with no other information regarding any other possible boards. The support is possible by enabling the SX1276 radio driver and the Lorawan stack on the Zephyr project configuration file.

Zephyr RTOS feature support are enabled on the prj.conf file by defining the feature that we want to enable. So for this testing the following features where enabled:

# Enable GPIO pins and the SPI interface for 
# communicating with the RF95W module

# Config USB support so that we can use a USB 
# to view log and debug information

# Point the console to the USB

# Enable the console, logging and the printk function

# Enable the SX12XX radio driver for Lora

# Enable the Lorawan stack
# Define the Lorawan region to be used: CONFIG_LORAMAC_REGION_EU868=y #CONFIG_LORAWAN_SYSTEM_MAX_RX_ERROR=90

All the above configuration enables the necessary components for building the Lorawan node: the SPI bus, GPIO, the SX1276 radio driver and LoraWan stack and finally logging to the USB console, where we can just use a simple terminal program to see what is going on, by can also use the printk function for the old style printf debugging…

Note that at this point we’ve haven’t defined neither the board that we will be using and the hardware interface to the Lora radio module, since the target hardware is defined at build time, not at configuration time.

Connecting the Lora Radio Module:
I’m using a RFM95W radio module that exposes some pins but not all from the SX1276 radio. To correctly work the LoraMac node library requires that each SX1276 radio DIO pins has its own associated GPIO pin (we can not merge DIO pins using diodes for example). For the several SX1276 DIO pins for Lora support, the DIO0 and DIO1 must be connected to the processor GPIO pins. The pins can be connected directly without any pull-downs or pull-ups.

The SX1276 radio module, and also by definition, the RF95W radio module that uses the SX1276 radio, use the SPI interface for communication, and so we must select what SPI bus we will use (if the board supports several SPI buses), and connect the associated SPI pins from the selected SPI bus to the RFM95W SPI pins.

To do this we need to define which SPI bus is used and how the RFM95W module is connected.

The Zephyr RTOS uses device trees to specify the connected hardware in a portable method, and comes “out of the box” with a series of predefined configurations for the hardware such SPI, I2C, UART, PWM, LED’s and so on.

If we want to change or add something to the hardware configuration, we need to create what is called an overlay file which for a specific board instance it defines or reconfigures the hardware, and overlays the new configuration over the default provided one.

In our Lorawan node we will be using the Blackpill STM32F411CE board, and for this board the Zephyr RTOS board name is blackpill_f411ce which means that we need to create a new overlay file for selecting which SPI bus we will be using and what pins the RFM95W radio module pins will be using. This configuration must be set on a file named blackpill_f411ce.overlay, and as we can see the filename must math the board name. This file must reside on the root of the project side by side with the prj.conf file or under a sub-directory named boards.

In my testing the RFM95W module will be connected to the SPI1 bus and for this board the pins are taken from the following map:

Blackpill F411 pinout

For the SPI1 bus we have:

  1. MISO – PA6
  2. MOSI – PA7
  3. SCLK – PA5

And these are the default SPI pins for the SPI1 bus that, if we need can we change to other alternate SPI1 bus pins through the overlay file. For now we just use the default pins.
To connect the RFM95W module, we need to define at least the chip select pin NSS, the DIO0 and DIO1 pins being other pins optional. Unlike the LMIC library where we could use LMIC_UNUSED_PIN, it seems that there isn’t such alternative on Zephyr.

So the pin mapping is now:

  1. NSS – PB12
  2. DIO0 – PA0
  3. DIO1 – PA1
  4. RESET – PA2

With the above settings our overlay file has now the following configuration:

&spi1 {
       status = “okay”;
       cs-gpios = <&gpiob 12 GPIO_ACTIVE_LOW>;

       lora: sx1276@0 {
                compatible = “semtech,sx1276”;
                reg = <0>;
                label = “sx1276”;
               reset-gpios = <&gpioa 3 GPIO_ACTIVE_LOW>;
               dio-gpios = <&gpioa 0 (GPIO_PULL_DOWN | GPIO_ACTIVE_HIGH)>,
                                    <&gpioa 1 (GPIO_PULL_DOWN | GPIO_ACTIVE_HIGH)>,
                                    <&gpioa 4 (GPIO_PULL_DOWN | GPIO_ACTIVE_HIGH)>,
                                   <&gpioa 4 (GPIO_PULL_DOWN | GPIO_ACTIVE_HIGH)>,
                                   <&gpioa 4 (GPIO_PULL_DOWN | GPIO_ACTIVE_HIGH)>,
                                   <&gpioa 4 (GPIO_PULL_DOWN | GPIO_ACTIVE_HIGH)>;
                rfi-enable-gpios = <&gpioa 4 GPIO_ACTIVE_HIGH>;
                rfo-enable-gpios = <&gpioa 4 GPIO_ACTIVE_HIGH>;
                pa-boost-enable-gpios = <&gpioa 4 GPIO_ACTIVE_HIGH>;
               tcxo-power-gpios = <&gpioa 4 GPIO_ACTIVE_HIGH>;
               tcxo-power-startup-delay-ms = <5>;
              spi-max-frequency = <1000000>;

/ {
     aliases {
         lora0 = &lora;

But the above file has a lot of unused pins mapped to GPIOA pin 4, that is really not correct or ideal.  If checking the following file: ZEPHYR_BASE/zephyr/dts/bindings/lora/semtech,sx1276.yaml we can see that some definitions are not required, and hence we can simplify our hardware configuration to only the RFM95 module pins that we really use:

&spi1 {
   status = “okay”;
   cs-gpios = <&gpiob 12  GPIO_ACTIVE_LOW>;

   lora: sx1276@0 {
       compatible = “semtech,sx1276”;
       reg = <0>;
       label = “sx1276”;
       reset-gpios = <&gpioa 3 GPIO_ACTIVE_LOW>;
       dio-gpios = <&gpioa 0 (GPIO_PULL_DOWN | GPIO_ACTIVE_HIGH)>,
                            <&gpioa 1 (GPIO_PULL_DOWN | GPIO_ACTIVE_HIGH)>;
       spi-max-frequency = <1000000>;
       power-amplifier-output = “pa-boost”;

/ {
   aliases {
      lora0 = &lora;

And this ends the hardware configuration for Zephyr RTOS with the RFM95W module on SPI1 bus.
We are now able to build our Lorawan TTN node for the Blackpill F411 board.

Building the Lorawan node code:
For building the Lorawan node code we must first installed and configured Zephyr RTOS so that we can use the west tool.

The code for the example is available here, and is derived from the class_a Lorawan Zephyr example, with added led blinking and USB logging so we can see what is going on. Beware that we need to first configure first the TTN keys (see below).

git clone
workon zephyr 
cd zLorawan_Node
west build -b blackpill_f411ce -p
west flash --runner openocd && sleep 2 && screen /dev/ttyACM0

For flashing I’m using the STLink connected to the board SWD pins, and since the Zephyr default for this board is DFU, we need to specify that we want to use StLink to flash it through the option –runner openocd.

We might need to press the reset button on the board so that the west flash tool works. A simple workaround to this is to edit the openocd.cfg file at (…)/zephyrproject/zephyr/boards/arm/blackpill_f411ce/support/ and add the reset_config none to the file:

source [find board/stm32f4discovery.cfg]
reset_config none

$_TARGETNAME configure -event gdb-attach {
    echo "Debugger attaching: halting execution"
    reset halt
    gdb_breakpoint_override hard

$_TARGETNAME configure -event gdb-detach {
    echo "Debugger detaching: resuming execution"

With this modification, flashing should work now without the need to press the reset button.

TTN Configuration:
Unlike the LMIC library, the key values for the necessary keys are taken directly in LSB format from the TTN console. So no need to convert anything to MSB format.
The Application EUI is called now JOIN_EUI and that is the value that we should put on that #define LORAWAN_JOIN_EUI.

Sample node output:
Reseting and connecting to the usb port provided by the board we now have the following output:

[00:00:00.130,000]  sx1276: SX1276 Version:12 found
[00:00:00.281,000]  lorawan.lorawan_init: LoRaMAC Initialized
[00:00:00.338,000]  usb_cdc_acm: Device suspended
[00:00:00.775,000]  usb_cdc_acm: Device configured
Starting up Lora node...
Starting Lorawan stack...
Joining TTN  network over  OTTA
[00:00:02.838,000]  lorawan.lorawan_join: Network join request sent!
Sending data...
[00:00:12.162,000]  lorawan.MlmeConfirm: Received MlmeConfirm (for MlmeRequest 0)
[00:00:12.162,000]  lorawan: Joined network! DevAddr: 260XXXXX
Data sent!
[00:00:16.131,000]  lorawan.McpsIndication: Received McpsIndication 0
[00:00:16.131,000]  lorawan.McpsConfirm: Received McpsConfirm (for McpsRequest 1)
[00:00:16.131,000]  lorawan.McpsConfirm: McpsRequest success!
[00:00:26.132,000]  lorawan: LoRaWAN Send failed: Duty-cycle restricted

And that’s it. Data should be shown now at the Device Traffic tab at the TTN Applications/Device console.


As some might be aware, I own a SDRPLAY RSP1A sdr receiver, and did some posts about it, specifically how to use it under Arch Linux.
One of my older posts shows how to make GQRX and SDRPlay RSP1A work together.

But since the last GQRX update, that post is deprecated since the issue that happened on the previous version doesn’t happen anymore on the new version, but still to make the GRPX and RSP1A play along together we need to change the device configuration, specifically the analog bandwidth to 8Mhz:

SDRPlay RSP1A GQRX device configuration

As we can see the bandwidth must be changed from the default 0Mhz to 8Mhz (or below to any multiple of 2) to show the full RSP1A bandwidth on the panadapter. Otherwise it only show a very small window of the captured radio spectrum, an issue much similar to the above linked post.

With this configuration, then we can see all the RSP1A 10Mhz bandwidth on the panadapter:

RSP1A GQRX panadapter

And now it works as it should.

Just a final note: I’m still using the SDRplay 2.13 driver and the standard SoapySDR and Soapysdrplay Arch Linux packages.

Some quick notes about Lorawan LMIC Library

I’m doing some testing with with several STM32 processors (STM32F103 Bluepill, Black STM32F407VE board and the newly arrived STM32F411CE blackpill board) and the RFM95 SX1276 Lora radio for connecting to the TTN Lorawan network. For the Arduino framework the MCCI LMIC library is now the library to use, since all the other alternatives have reached end of life.

For the RFM95W radio module I’m using either the Hallard RFM95W Wemos Lora shield or the DIYcon_nl Lora shield. Please note that on this board, the thickness of the PCB is a bit greater than used by SMA edge mount pin gap intervals, so we need to bend the pins a bit to be able to solder the SMA connector.

Anyway, for the Hallard shield to work, since it “merges” all Lora DIO# pins through diodes to a single pin, a 10K pull down resistor is required to be able to work with the STM32 boards, since even with GPIO pulldown enabled I had issues with the STM32 detecting the state transition. With the resistor everything works fine. This was done since the ESP8266 Wemos board hasn’t enough pins to connect SPI + CS + DIO# pins. This doesn’t happen on the STM32 Bluepill and Blackpill and of course much less on the F407VE black board where we can use all the RFM95W/SX1276 pins.

As I said initially, this post is just some quick notes of what I’ve found when using the library with the above hardware.

This error is good, since it means that at hardware level everything might be 100% functional.
This issue happens when using the TTN OTAA method the APPEUI, now with the latest Lorawan releases called JOINEUI and DEVEUI are not in LSB format.
Double check the EUI format, and change the order if necessary.

Assert error at radio.c:1065
This error comes from the ASSERT( (readReg(RegOpMode) & OPMODE_MASK) == OPMODE_SLEEP ); radio.c:1065 line.
This is an hardware error. It could be a problematic RF95W module, but so far every instance of this error was caused by the following issues:

1 – Bad wiring
The most obvious issue is just bad wiring/connection, either to the SPI bus or the NSS (chip select) line. Check and double check that the SPI pins used on the STM32 are the correct ones.
For example for the BluePill and the BlackPill the SPI1 bus pins are MISO1 -> PA6, MOSI1 -> A7, SCLK1 -> A5. The NSS pin can be defined on LMIC pin definitions, which takes us to the other possible error:

2 – Bad LMIC pin definition
For the LMIC stack to work, at least the NSS, DIO0 and DIO1 pins must be defined correctly. Without NSS, the RFM95W is never select and hence will never receive the necessary commands to transmit or receive. The correct DIO# pins definition is critical since these indicate when TX and RX have ended and allow the library to retrieve or send more data.
An example that I’m using on the Blackpill F411ce board is as following:

// Pin mapping
const lmic_pinmap lmic_pins = {
    .nss = PB12,
    .rxtx = LMIC_UNUSED_PIN,
    .rst = PA3,
    .dio = {PA0, PA1, PA2},
    //.spi_freq = 4000000

Your settings might not be equal, but NSS, DIO0 and DIO1 are mandatory (DIO0 = PA0, DIO1 = PA1 in my case). I have PA2 defined for DIO2, but it can be LMIC_UNUSED_PIN without any consequences.

3 – Again bad wiring
As we can see bad wiring has a lot of influence in how successful we are using the RFM95W module, but in this case even we checked and double checked that everything looks correctly defined, it still doesn’t work and gives uses the radio.c:1065 line assert error.
In all cases that I had with this error it was again bad wiring including cold solder joints.

  • Bad dupont cable
  • Colder solder joint on the NSS pin
  • Bad solder joint on the GND(!) pin

So check all the wires and solder joints for continuity, and if they look suspicious, remake them again. In one of the cases, it was the GND RFM95 board pin, that despite having a blob of solder it didn’t make a proper contact. Also look for shorts and after soldering clean any flux residues to clear out any shorts possibility.

And that’s it. I’ll probably update this post as I find issues along the way.

Setting the SPI interface for Lorawan TTN LMIC

I’m messing around with the Lorawan library LMIC, specifically the more supported MCCI LoRaWAN LMIC library that is supported on several platforms, including the STM32 platform based boards.

While the library worked out of the box on specifically the STM32F103 blue pill and the STM32F407ve black board when using SPI1 bus without any issue, a question popped up: What if I want to SPI2 for example on the STM32F407ve black board instead of the default SPI1 bus for connecting the RFM95W transceiver?

The solution is easy, and works fine if using the ST STM32 Arduino core: Before initializing the LMIC stack we set the SPI pins for the bus we want to use:

    // LMIC init
    SPI.setMOSI(PC3);       // Use SPI2 on the STM32F407ve board.

    // Reset the MAC state. Session and pending data transfers will be discarded.

Note that this changes the SPI configuration used by the LMIC library which may impact other libraries that use the same SPI global variable. So we need to take caution with this possible side effect.

With this change, LMIC library works as expected by using the Lora transceiver on the SPI2 bus.

STM32 Blue Pill board, Arduino Core and USB serial output on Platformio

So I’m testing out some different language, frameworks and programming methods on STM32 using the cheap and readily available STM32F103 blue pill board.

So far I had no troubles using the USB connector as a serial device on STM32CubeIDE, CubeMX and the Zephyr RTOS.

So anyway, to keep the story (and the post short), while using the Arduino Core for STM32 and the PlatformioIO platform for doing some tests, I’ve found out that the USB Serial output didn’t worked as expected.

I did know that this issue was not with the board, since all the other frameworks/platforms had no trouble using the USB port for serial output, so I did know that the issue was due to a software and/or configuration issue.

After some searching around, the solution, while not complete was found on this Platformio forum post.

In my case I still had some errors after the original recommend configuration:

platform = ststm32
board = bluepill_f103c8
framework = arduino
upload_protocol = stlink
build_flags =
    -D USBD_VID=0x0483
Compiling .pio/build/bluepill_f103c8/FrameworkArduino/wiring_digital.c.o
/home/pcortex/.platformio/packages/framework-arduinoststm32/cores/arduino/stm32/usb/usbd_desc.c:46:4: error: #error "USB VID or PID not specified"
   46 |   #error "USB VID or PID not specified"
      |    ^~~~~
In file included from /home/pcortex/.platformio/packages/framework-arduinoststm32/system/Middlewares/ST/STM32_USB_Device_Library/Core/Inc/usbd_core.h:30,
                 from /home/pcortex/.platformio/packages/framework-arduinoststm32/cores/arduino/stm32/usb/usbd_desc.c:21:
/home/pcortex/.platformio/packages/framework-arduinoststm32/cores/arduino/stm32/usb/usbd_desc.c:160:10: error: 'USBD_PID' undeclared here (not in a function); did you mean 'USBD_VID'?
  160 |   LOBYTE(USBD_PID),           /* idProduct */
      |          ^~~~~~~~
/home/pcortex/.platformio/packages/framework-arduinoststm32/system/Middlewares/ST/STM32_USB_Device_Library/Core/Inc/usbd_def.h:275:32: note: in definition of macro 'LOBYTE'
  275 | #define LOBYTE(x)  ((uint8_t)((x) & 0x00FFU))

This was easyly solved by adding the PID (Product ID) to the configuration settings:

platform = ststm32
board = bluepill_f103c8
framework = arduino
upload_protocol = stlink
build_flags =
    -D USBD_VID=0x0483
    -D USBD_PID=0x0100

and low and behold, Serial.println() works as expected and the bluepill is detected at USB label with the VID and PID settings above defined:

Bus 001 Device 024: ID 0483:0100 STMicroelectronics STM32 STLink


Just a final note, all Serial.### functions could now be replaced by SerialUSB.###, for example:


SerialUSB.println(“Hello world\n”);

But standard Serial.## functions work now with output redirected to the USB virtual COM port.

Zephyr RTOS sample project with the STM32 blue pill board.

So this post describes more or less in detail how to build a small Zephyr RTOS project using as a target the famous and cheap STM32 blue pill board that has a ST32F103 ARM processor onboard an it is supported by Zephyr RTOS.
The project is quite simple, but it will show how to:

  1. Create a project from scratch.
  2. Create RTOS tasks
  3. Enable USB console

Creating a Zephyr RTOS project
Has documented in my previous post Zephyr RTOS – Initial setup and some tests with Platformio and the NRF52840 PCA10059 dongle and also on Zephyr documentation, we need to download, install and configure the Zephyr RTOS sources, the west tool and the supporting Zephyr SDK. This is explained on the above post.

We can create our project under the zephyr workspace directory, but then we will have trouble if we want to use git to manage our project since the zephyr workspace directory is already a git repository. So we will create our own directory outside of the zephyr workspace directory and work from there.
To do this we need to set the ZEPHYR_BASE environment variable to point to the zephyr workspace, otherwise the west tool that will compile and flash our project will fail. Since west is a python command and we are using virtual environments, as discussed on the previous post we need to first change to the virtual env that has west installed:

workon zephyr

We can now setup our project:

mkdir zSTM32usb
export ZEPHYR_BASE=/opt/Develop/zephyrproject/zephyr
cd zSTM32usb

Because I don’t want to create all the necessary files from scratch, mainly the CMakeLists.txt file, I just copy from the zephyr samples repository the simplest of the projects, blinky:

cp -R /opt/Develop/zephyrproject/zephyr/samples/basic/blinky/* .

At this point we should be able to compile and flash the STM32 blue pill board, but before that we can change the name of the project on the CMakeLists.txt file just for consistency:

# SPDX-License-Identifier: Apache-2.0

cmake_minimum_required(VERSION 3.13.1)

target_sources(app PRIVATE src/main.c)

We can now compile the project:

west build -b stm32_min_dev_blue

or if we want to do a clean build we add the -p (pristine) flag:

west build -b stm32_min_dev_blue -p

And it should compile without any issues since this is still the basic blinky project.

-- Configuring done
-- Generating done
-- Build files have been written to: /opt/Develop/zSTM32usb/build
-- west build: building application
[1/138] Preparing syscall dependency handling

[133/138] Linking C executable zephyr/zephyr_prebuilt.elf
Memory region         Used Size  Region Size  %age Used
           FLASH:       27064 B        64 KB     41.30%
            SRAM:       12392 B        20 KB     60.51%
        IDT_LIST:         184 B         2 KB      8.98%
[138/138] Linking C executable zephyr/zephyr.elf

If we didn’t set correctly the ZEPHYR_BASE environment variable, we will get some errors. For example for listing out the available target boards, we can do a west boards command:

west boards
usage: west [-h] [-z ZEPHYR_BASE] [-v] [-V]  ...
west: error: argument : invalid choice: 'boards' (choose from 'init', 'update', 'list', 'manifest', 'diff', 'status', 'forall', 'help', 'config', 'topdir', 'selfupdate')

With the variable ZEPHYR_BASE (and virtual environment) correctly set, we get:

west boards | grep stm32

So make sure the environment is correctly set.

Flashing the board:
Flashing the board is as easy as doing:

west flash

To be able to do this is necessary to have a ST-Link programmer and that it is properly connected to the STM32 blue pill board. Any issues here are probably not related with Zephyr or the west tool, since west only calls openocd to flash the board.

 west flash
-- west flash: rebuilding
[0/1] cd /opt/Develop/zSTM32USB/build/zephyr/cmake/flash && /usr/bin/cmake -E echo

-- west flash: using runner openocd
-- runners.openocd: Flashing file: /opt/Develop/zSTM32USB/build/zephyr/zephyr.hex
Open On-Chip Debugger 0.10.0+dev-01341-g580d06d9d-dirty (2020-05-16-15:41)
Licensed under GNU GPL v2
For bug reports, read
Info : auto-selecting first available session transport "hla_swd". To override use 'transport select '.
Info : The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD
Info : clock speed 1000 kHz
Info : STLINK V2J36S7 (API v2) VID:PID 0483:3748
Info : Target voltage: 3.212648
Info : stm32f1x.cpu: hardware has 6 breakpoints, 4 watchpoints
Info : Listening on port 3333 for gdb connections
    TargetName         Type       Endian TapName            State       
--  ------------------ ---------- ------ ------------------ ------------
 0* stm32f1x.cpu       hla_target little stm32f1x.cpu       running

target halted due to debug-request, current mode: Thread 
xPSR: 0x01000000 pc: 0x08002378 msp: 0x20002768
Info : device id = 0x20036410
Info : flash size = 64kbytes
auto erase enabled
wrote 27648 bytes from file /opt/Develop/zSTM32USB/build/zephyr/zephyr.hex in 1.769166s (15.261 KiB/s)

target halted due to debug-request, current mode: Thread 
xPSR: 0x01000000 pc: 0x08002378 msp: 0x20002768
verified 27064 bytes in 0.404006s (65.419 KiB/s)

shutdown command invoked

And now we should have a blinking led.

Creating a project from scratch – Conclusion:
So we now have a project base that we can use that it’s outside of the zephyr workspace directory, and hence, can have it’s own git repository without clashing with the zephyr workspace repository.

We can now move to add functionality to our project.

Creating the RTOS tasks
The basic blinky sample program uses a simple main() entry point and does not create any tasks so it is as simple as it can get.

A single threaded program, like it is blinky, has a main function, and it might have other tasks, either created dynamically or statically.

In our example, we will create the tasks statically. As we can see in the main.c file for our example at the zSTM32usb Github repository we define tasks by using the predefined macro K_THREAD_DEFINE:

// Task for handling blinking led.
K_THREAD_DEFINE(blink0_id, STACKSIZE, blink0, NULL, NULL, NULL, PRIORITY, 0, 0);    

// Task to initialize the USB CDC ACM virtual COM port used for outputing data.
// It's a separated task since if nothing is connected to the USB port the task will hang...
K_THREAD_DEFINE(console_id, STACKSIZE, usb_console_init, NULL, NULL, NULL, PRIORITY, 0, 0);

According to K_THREAD_DEFINE Zephyr documentation the parameters are as follows:

K_THREAD_DEFINE(name, stack_size, entry, p1, p2, p3, prio, options, delay)
        name: Name of the thread.
        stack_size: Stack size in bytes.
        entry: Thread entry function.
        p1: 1st entry point parameter.
        p2: 2nd entry point parameter.
        p3: 3rd entry point parameter.
        prio: Thread priority.
        options: Thread options.
        delay: Scheduling delay (in milliseconds), or K_NO_WAIT (for no delay).

Based on this, we can then fine tune the task parameters, for example the stack size that is globally defined as 1024 bytes (way too much), and produces an image that takes around 12K of SRAM:

[133/138] Linking C executable zephyr/zephyr_prebuilt.elf
Memory region         Used Size  Region Size  %age Used
           FLASH:       27064 B        64 KB     41.30%
            SRAM:       12392 B        20 KB     60.51%
        IDT_LIST:         184 B         2 KB      8.98%
[138/138] Linking C executable zephyr/zephyr.elf

where if we cut the stacksize to 512 bytes, if frees up SRAM, which is now arounf 11K:

[133/138] Linking C executable zephyr/zephyr_prebuilt.elf
Memory region         Used Size  Region Size  %age Used
           FLASH:       27064 B        64 KB     41.30%
            SRAM:       11368 B        20 KB     55.51%
        IDT_LIST:         184 B         2 KB      8.98%
[138/138] Linking C executable zephyr/zephyr.elf

So while in this example the stack size is equal to both tasks, in a reality each task should have it’s stack adjusted to make the most of the available SRAM/RAM.

Also since the tasks are cooperative they need to release the processor to other tasks so they can run, hence instructions that wait for resources, or just a simple sleep are required to let all tasks to run cooperatively.

In our example this is achieved by the sleep instruction k_msleep that sleeps the tasks for the miliseconds that is passed as the parameter.

For example for blinking the Led, we have:

    // Blink for ever.
    while (1) {
	gpio_pin_set(gpio_dev, led->gpio_pin, (int)led_is_on);
	led_is_on = !led_is_on;
	k_msleep(SLEEP_TIME_MS);    // We should sleep, otherwise the task won't release the cpu for other tasks!

Tasks description:
Not too much to say about them, except if they do not enter a infinite loop, like the above led blinking while loop, the task does what it has to do and it ends.

Specifically for our example the led blinking task uses the Zephyr Device Tree to retrieve the onboard led configuration, and then, with that configuration it can start blinking the led. This opens the possibility of handling multiple blinking leds with the same code, just by creating a new task for each led.

The usb console init task, initiates the USB console port and waits for a port connection, after the connection happens, it starts printing to the console using the printk function. If we connect to the USB port of the STM32 blue pill board we get: /dev/ttyACM0
Hello from STM32 CDC Virtual COM port!

Hello from STM32 CDC Virtual COM port!


By experience console output that isn’t used for debugging purposes and/or while in development should be centralized on a single task because: first it will avoid concurrency issues between multiple tasks, and second if nothing is connected to the USB port to consume the console data, the tasks won’t hang waiting for a USB terminal connection to consume the console output.

USB Console Output configuration:
The end this already long post, we need to configure the console output to goto the USB virtual com port. This USB com port is only used for the console output, not for bidirectional communication such as an user and the device using a terminal program.

The configuration is done on the Zephyr configuration project file prj.conf, and the necessary information to enable USB console output was gathered from a series of different sources….



A simple and quick description to the above file is that this file enables a set of modules, and provides some configuration to those modules to be able to use them. An example, to use the Led, the Led is connected to a GPIO pin, so it is necessary to enable the GPIO module: CONFIG_GPIO=y.
The same is true to enable USB. It’s necessary to enable USB support and the USB stack. Some console configuration is needed such as the CONFIG_USB_UART_CONSOLE=y, since the original, it seems, console output is to an UART port.

We can see the USB port connected when reseting the board after flashing:

[30958.705584] usb 1-1.2: new full-speed USB device number 7 using xhci_hcd
[30958.818608] usb 1-1.2: New USB device found, idVendor=2fe3, idProduct=0100, bcdDevice= 2.04
[30958.818610] usb 1-1.2: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[30958.818611] usb 1-1.2: Product: Zephyr Console
[30958.818611] usb 1-1.2: Manufacturer: ZEPHYR
[30958.818612] usb 1-1.2: SerialNumber: 8701241654528651
[30958.880665] cdc_acm 1-1.2:1.0: ttyACM0: USB ACM device

and on the device list:

Bus 001 Device 003: ID 0483:3748 STMicroelectronics ST-LINK/V2
Bus 001 Device 007: ID 2fe3:0100 NordicSemiconductor STM32 STLink

where the first entry is indeed the ST-Link programmer, and the the second entry is our USB console port.

As a final note, during compilation, a warning about the device id 2fe3:0100 is given, since for production use we need to change the default:

CMake Warning at /opt/Develop/zephyrproject/zephyr/subsys/usb/CMakeLists.txt:22 (message):
  CONFIG_USB_DEVICE_VID has default value 0x2FE3.

  This value is only for testing and MUST be configured for USB products.

CMake Warning at /opt/Develop/zephyrproject/zephyr/subsys/usb/CMakeLists.txt:28 (message):
  CONFIG_USB_DEVICE_PID has default value 0x100.

  This value is only for testing and MUST be configured for USB products.

As usual we can change this by changing the VID on the prj.conf file.


And that’s it. We now have a minimal skeleton where we can start build some applications and have some console output either for tracing or general information.
The neat part is while I’ve tested this with a STM32 Blue pill board, the same code works without any modification on other boards such as the NRF52840 dongle, which shows that with the same code base we can target different boards.

Upgrading the Arduino MKRWAN Murata Lora module firmware

The Arduino MKRWan 1300 (there is also an improved version MKRWan 1310 that solves some low power issues), is an Arduino compatible board with a SAMD21 ARM processor and a Murata (CMWX1ZZABZ version 078) Lora module that internally has an STM32L0 processor and the Lora transceiver. The STM32L0 Murata module has it’s own firmware that presents an AT modem command type interface to the SAMD21 processor.

While doing some tests I’ve found out that my modules had different Murata firmware versions: 1.1.2, 1.1.5, and so some of the AT commands failed, such as the command to set FPORT AT+PORT that only existed on the 1.1.5 firmware version (or above).

Upgrading the firmware:
My first approach was to download the latest firmware release from the MKRWAN-fw releases and using the Firmware serial bridge combined with the specific STM32 flasher. With this combination it seemed that it was able to flash the STM32L0 through the serial port but I ended up with a bootable Murata module (Could see the +EVENT messages) but no response from the AT commands, so in fact it seemed that I’ve bricked the Murata modules. Reverting to an older firmware version using the same method also exhibited the same behavior.
An example of such upload is as follows:

./stm32flash -b 115200 -e 0 -w mlm32l07x01.bin /dev/ttyACM0 
stm32flash 0.5

Using Parser : Raw BINARY
Interface serial_posix: 115200 8E1
Version      : 0x31
Option 1     : 0x00
Option 2     : 0x00
Device ID    : 0x0447 (STM32L07xxx/08xxx)
- RAM        : Up to 20KiB  (8192b reserved by bootloader)
- Flash      : Up to 192KiB (size first sector: 32x128)
- Option RAM : 32b
- System RAM : 8KiB
Write to memory
Wrote address 0x08012ce4 (100.00%) Done.

I’ve also needed to add the -e 0 to not erase the pages, or otherwise the stm32flash failed with an memory erase error so that the command was able to run (it seemed) successfully.
This is probably the issue why the Firmware flashing while sucessufull still ended up with a non responsive module.

Anyway, after some fiddling, there is no need to do anything above. On the MKRWAN library on the examples folder there is a standalone flashing utility with the firmware embedded on the file fw.h as all in one solution. More, the firmware provided seems to be more recent that the MKRWan FW releases folder, version 1.2.0 where on the releases folder it was 1.1.9 with only 1.1.6 providing the binary file.

So all we need is to compile and upload the standalone firmware upload, and it worked straight away: /dev/ttyACM0 
--- Miniterm on /dev/ttyACM0  9600,8,N,1 ---
--- Quit: Ctrl+] | Menu: Ctrl+T | Help: Ctrl+T followed by Ctrl+H ---
Press a key to start FW update
Version      : 0x31
Option 1     : 0x00
Option 2     : 0x00
Device ID    : 0x0447 (STM32L07xxx/08xxx)
- RAM        : Up to 20KiB  (8192b reserved by bootloader)
- Flash      : Up to 192KiB (size first sector: 32x128)
- Option RAM : 32b
- System RAM : 8KiB
Write to memory
Erasing memory
Wrote and verified address 0x08000100 (0%)
 Wrote and verified address 0x08000200 (0%)
 Wrote and verified address 0x08000300 (1%)
 Wrote and verified address 0x08000400 (1%)
 Wrote and verified address 0x08000500 (1%
 Wrote and verified address 0x08012c00 (100%)

Starting execution at address 0x08000000... done.
Flashing ok :)
ARD-078 1.2.0

The odd thing is that the firmware updating is on the Github project for the client Lorawan project, the MKRWan lib and not on the MKRWAN Firmware project.

Using a small terminal/Murata bridge

#include <Arduino.h>

void setup() {   
  // Wait for console
  while (!Serial);

  Serial2.begin(19200);                  // Connect to the Murata module through the Serial2 port at 19200

  pinMode(LORA_BOOT0, OUTPUT);
  digitalWrite(LORA_BOOT0, LOW);
  digitalWrite(LORA_RESET, HIGH);
  digitalWrite(LORA_RESET, LOW);
  digitalWrite(LORA_RESET, HIGH);

  Serial.println("Enter AT commands to talk to the Murata module...");

void loop() {
	if ( Serial.available() != 0 ) {
		while ( Serial.available() > 0 ) {
			char c =;
                if ( c == '\n' ) c = '\r';
		Serial2.print( c );						
		Serial.print( c );						
		if ( c == '\r' )

	if ( Serial2.available() != 0 ) {
		while ( Serial2.available() > 0 ) {
			char c =;
			Serial.print( c );						
			if ( c == '\r' )

With this simple sketch flashed onto the MKRWAN board, we can now talk directly to the Murata Module using AT commands, without any dependency from the MKRWAN lib, and hence do any tests that we might want. In my case was just to test:



Improving SDR reception

The next few lines won’t probably add nothing new to a seasoned user or ham operator, but might help some one that stumbles on this post. So anyway here are some tips that might help anyone that is in the same situation as I.

The issue of living an apartment with few options for deploying antennas can be challenging for receiving anything in the HF bands.
So for a long time I have an SDRPlay RSP1A that covers from low frequency bands to UHF bands and above. But while I’m more or less successful to receive UHF 430MHz bands, I hadn’t much luck in lower bands. With exceptions for the FM frequencies, where I have nearby 50Kw transmitters and can pick up FM without any issues, all spectrum below 200MHz is noise and more noise.

So some steps that I took to improve things up and their outcomes:

Ferrite beads on the USB cable:
I added two clip on ferrite beads to the USB cable, right at the connection point to the SDRPlay, to see if any USB noise was affecting reception, but no change. Anyway I just left the beads on the cable, since it seems that RSP1A is not affected but USB noise at the HF bands. Verdict: No measurable improvements.

Better RSP1A shielding:
The RSP1A comes within a plastic case, but according to some people (I didn’t open it to check it), the inner case has some shielding. I tried some sort of shielding either with an external metal case, tin foil wrapping (yes I know… 🙂 ), but no measurable influence. Verdict: No measurable improvements.

Ferrite Core at the antenna input:
This was a game changer. Adding a power cord ferrite core just before the antenna sma connector on the RSP1A cleared a lot of noise and some other artifacts:

Before connecting to the SMA connector the antenna cable makes some loops on the ferrite as shown above and then it connects to the RSP1A.
While I still am deaf at a lot of bands, including the 80, 40 a 2 meter bands, I can here now FT8 on the 20m band and decoding it. At night I can also hear some ham radio chatter, all this while using a simple 9:1 unun and a random lenght wire antenna. Verdict: Good measurable improvement!.
(This is wahat is supposed called a common mode choke.)

I did some other changes, but all of them are now antenna related which leads us to the conclusion:

All this just points to a what is evident from the beginning: Better antennas are need to improve reception, and while some basic things can improve reception, such as the ferrite core at the antenna output, there is no escape to getting a better antenna.

Zephyr RTOS – Initial setup and some tests with Platformio and the NRF52840 PCA10059 dongle

This posts shows a quick how to for installing and configuring the Zephyr RTOS project on Arch Linux. In reality this post is a mashup of already a set of instructions and tutorials from the Zephyr project home page and also Adafruits Zephyr instructions:

  1. Zephyr RTOS Generic install instructions:
  2. Adafruits install instructions with setting up Pythons virtual environments:
  3. Specific instructions from the Zephyr RTOS project documentation for Arch Linux:

By mashing up all the collected instructions from the above link, here it is my instructions:

Install some needed packages for Arch Linux:

sudo pacman -S git cmake ninja gperf ccache dfu-util dtc wget python-pip python-setuptools python-wheel tk xz file make

Check Python:
Note that Python2 is discontinued, and so all Python programs and packages are for Python 3 version.

One thing that I also had messed up was that the default Python environment on one of my machines was using Platformio penv directory, instead of the Python3 global environment. Make sure that we are using the global environment and not other non global environment.

A (better) approach as described on the Adafruit tutorial is to use Python virtual environments and so we need to install virtual environment support:

sudo pip3 install virtualenv virtualenvwrapper

and we need to change the .bashrc file at our home directory to add virtual environment support:

# For using Python and Venvs
export PATH=~/.local/bin:$PATH
export WORKON_HOME=$HOME/.virtualenvs
export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
source /usr/bin/

Execute now source ~/.bashrc to load the new configuration

Since we will load our firmware on the NRF52840 dongle through DFU we also install the nrfutil:

pip install nrfutil

Installing Zephyr RTOS:
I’ll be installing the Zephyr RTOS files and SDK on /opt/Develop:

mkvirtualenv zephyr

mkdir /opt/Develop
cd /opt/Develop
mkdir zephyrproject

workon zephyr
pip install west nrfutil
west init ./zephyrproject

cd zephyrproject
west update

we also installed the nrfutil utility on this virtual environment.

To end the Zephyr RTOS setup we install the also the latest requirements:

pip install -r zephyr/scripts/requirements.txt

and that’s it.

Installing the SDK:
We can install the SDK on some of the predefined directories or our own directories, just make sure that in the later case some environmental variables are set to allow the Zephyr RTOS find the SDK:


(zephyr) [pcortex@pcortex:Develop]$ ./
Verifying archive integrity... All good.
Uncompressing SDK for Zephyr  100%  
Enter target directory for SDK (default: /home/pcortex/zephyr-sdk/): /opt/Develop/zephyr-sdk-0.11.3

It is recommended to install Zephyr SDK at one of the following locations for automatic discoverability in CMake:

Note: The version number '-0.11.3' can be omitted.

Do you want to continue installing to /opt/Develop/zephyr-sdk-0.11.3 (y/n)?
md5sum is /usr/bin/md5sum
Do you want to register the Zephyr-sdk at location: /opt/Develop/zephyr-sdk-0.11.3
  in the CMake package registry (y/n)?
/opt/Develop/zephyr-sdk-0.11.3 registered in /home/pcortex/.cmake/packages/Zephyr-sdk/847bb3ddf638ff02dce20cf8dc171b02
Installing SDK to /opt/Develop/zephyr-sdk-0.11.3
Creating directory /opt/Develop/zephyr-sdk-0.11.3
 [*] Installing arm tools...
 [*] Installing arm64 tools...
 [*] Installing arc tools...
 [*] Installing nios2 tools...
 [*] Installing riscv64 tools...
 [*] Installing sparc tools...
 [*] Installing x86_64 tools...
 [*] Installing xtensa_sample_controller tools...
 [*] Installing xtensa_intel_apl_adsp tools...
 [*] Installing xtensa_intel_s1000 tools...
 [*] Installing xtensa_intel_bdw_adsp tools...
 [*] Installing xtensa_intel_byt_adsp tools...
 [*] Installing xtensa_nxp_imx_adsp tools...
 [*] Installing xtensa_nxp_imx8m_adsp tools...
 [*] Installing CMake files...
 [*] Installing additional host tools...
Success installing SDK.

You need to setup the following environment variables to use the toolchain:

     export ZEPHYR_SDK_INSTALL_DIR=/opt/Develop/zephyr-sdk-0.11.3

Update/Create /home/pcortex/.zephyrrc with environment variables setup for you (y/n)?
SDK is ready to be used.

and the new .bashrc configuration is now:

# For using Python and Venvs
export PATH=~/.local/bin:$PATH
export WORKON_HOME=$HOME/.virtualenvs
export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
source /usr/bin/

export ZEPHYR_SDK_INSTALL_DIR=/opt/Develop/zephyr-sdk-0.11.3

If we do not add the lines to the .bashrc file when starting up a project or working on it, we need to execute the script on the Zephyr Rtos project directory.

Flashing the Blink sample program on the NRF52840 dongle:

This is pretty much documented on the NRF52840 Dongle page at NRF52840 Dongle documentation.

In our case is just something like:

cd /opt/Develop/zephyrproject
echo Select the PEnv zephyr
workon zephyr
west build -b nrf52840dongle_nrf52840 zephyr/samples/basic/blinky
nrfutil pkg generate --hw-version 52 --sd-req=0x00 --application build/zephyr/zephyr.hex --application-version 1

and now we need to plugin and enable the dongle dfu mode to flash the firmware:

nrfutil dfu usb-serial -pkg -p /dev/ttyACM0

and the green led on the board should start to blink.

Using Platformio:
While the NRF52840 development kit from Nordic is supported (PCA10056) in both Zephyr and Platformio, the dongle version (PCA10059) is only supported on Zephyr. Since DFU upload is not supported for these boards, so we need some trickery to be able to do it from the Platformio Upload command.

To use to Platformio to target the dongle board, a project targeting the NRF52840_DK board and the Zephyr framework is created and then modifying the platformio.ini we can also target the dongle. For uploading the firmware a custom upload script is used that uses nrfutil to create a non signed DFU package and upload it.

platform = nordicnrf52
board = nrf52840_dk
framework = zephyr
board_build.zephyr.variant = nrf52840dongle_nrf52840
extra_scripts =
upload_protocol = custom

platform = nordicnrf52
board = nrf52840_dk
framework = zephyr

For the NRF52840 dongle we pass to the Platformio build system the board variant used by Zephyr that targets the dongle, which is the nrf52840dongle_nrf52840 (where it was previously nrf52840_pca10059). Since the dongle hasn’t an on board debugger for uploading firmware through JTAG/Stlink, we need to use a custom upload method with an associated python script:

import sys
import os
from os.path import basename

platform = env.PioPlatform()

def dfu_upload(source, target, env):
    firmware_path = str(source[0])
    firmware_name = basename(firmware_path)

    genpkg = "".join(["nrfutil pkg generate --hw-version 52 --sd-req=0x00 --application ", firmware_path, " --application-version 1"])
    dfupkg = "nrfutil dfu usb-serial -pkg -p /dev/ttyACM0"
    print( genpkg )
    os.system( genpkg )
    os.system( dfupkg )

    print("Uploading done.")

# Custom upload command and program name
env.Replace(PROGNAME="firmware", UPLOADCMD=dfu_upload)

This file is put side by side with the platformio.ini file and has some hardcoded values, such as the upload port, but it gets the job done.