Zephyr Example 1: Blinky

Setting up Zephyr Environment

Detailed description about Zephyr environment can be found here. Since most of the prerequisites are common to other development, chances are you already have them installed on your computer. Ubuntu and its derivative users may need to uninstall outdated device-tree-compiler package and install new one by building from the source.

Running a Sample Code

Grab one of the board listed as supported, clone the Zephyr source tree, go to one of the sample code directory and run:

    1 source (Zephyr_Root)/zephyr-env.sh
    2 mkdir build && cd build
    3 cmake -GNiinja DBOARD=(your_board)
    4 ninja
    5 ninja flash

Here (Zephyr_Root) is the root directory of the SDK. Board name (your_board) can be found under (Zephyr_Root)/boards/

Default CMake generator is “Unix Makefile”. However ninja is way more faster at least in Zephyr. You can specify Ninja at the command line as shown above. Or you can override it by creating a file named PreLoad.cmake with following content and put it in the same directory as CMakeLists.txt.

    1 set (CMAKE_GENERATOR "Ninja" CACHE INTERNAL "" FORCE)

Additionally you can set the board in the CMakeLists.txt so you don’t have to specify that as well in the command line.

    1 cmake_minimum_required(VERSION 3.8.2)
    2 set(BOARD disco_l475_iot1)
    3 include($(ENV{ZEPHYR_BASE}/cmake/app/boilerplate.cmake NO_POLICY_SCOPE)

Note that this line comes before including the boilerplate setting.

Blinky

We are going to use ST Disco L475 IoT01 board in this example and examples in the posts follows. To control the GPIO, you need to have proper Kconfig settings. This is usually done by adding following line to the prj.conf file:

    1 CONFIG_GPIO=y

However it is likely done already when you specify your board above. Check the defconfig file for your board under Zephyr SDK directory. In this case, it is

(SDK_ROOT)/boards/arm/disco_l475_iot1/disco_l475_iot1_defconfig 

Write a main.c

    1 #include <zephyr.h>
    2 #include <misc/printk.h>
    3 #include <gpio.h>
    4 
    5 #define LED_PORT        DT_GPIO_STM32_GPIOC_LABEL
    6 #define LED_PIN         9
    7 
    8 void main(void)
    9 {
   10     int cnt = 0;
   11     struct device *dev;
   12 
   13     dev = device_get_binding(LED_PORT);
   14     gpio_pin_configure(dev, LED_PIN, GPIO_DIR_OUT);
   15 
   16     while (1) 
   17     {
   18         gpio_pin_write(dev, LED_PIN, cnt % 2);
   19         cnt++;
   20         k_sleep(500);
   21     }
   22 }

And run ninja again. Port name on line number 5 can be found under

(SDK_ROOT)/soc/arm/st_stm32/stm32l4/dts_fixup.h

Leave a comment