Category: Dicas NuttX

NuttX Channel #016: Using the HC-SR04 to measure distance

I create a new video explaining how to use the ranging sensor HC-SR04 on NuttX:


Creating a HC-SR04 driver for NuttX

In this post I will explain how I did the HC-SR04 driver for NuttX.

I think this is the first time I try to explain how to create a driver for NuttX, oh wait! It is not! The first time was this post: NuttX driver to control a single LED

But this time it will be different, instead of just posting the code here, I will try to explain how I came with the driver. So, let to get started.

First I searched for the HC-SR04 datasheet, it was easy to find:

Reading it I discovered that I need to send a pulse of 10uS in the pin Trig to start the conversion, pretty easy:

static int hcsr04_start_measuring(FAR struct hcsr04_dev_s *priv)
  /* Configure the interruption */

  priv->rising = true;
  priv->config->irq_setmode(priv->config, priv->rising);
  priv->config->irq_enable(priv->config, true);

  /* Send to 10uS trigger pulse */

  priv->config->set_trigger(priv->config, true);
  priv->config->set_trigger(priv->config, false);

  return 0;

After sending the Trigger pulse we will receive a pulse in the Echo pin with the width encoding the distance measured.

Because we need to measure width of a pulse the first idea that came to my mind was to use the Input Capture of STM32 Timer (I’m using the STM32F103-Minimum board), but I want this driver to be generic, then I decided to use an ordinary GPIO interrupt pin of STM32.

I can setup STM32 to detect level changing (rising edge and falling edge), but some microcontrollers don’t support it, you need to select rising edge or falling edge, not both at same time. We need to work around it because I need this driver to be generic enough to work on these “poor man” MCUs.

Then to get it working I need to implement a ping-pong approach: first setup the GPIO pin to detect rising edge of signal and inside the ISR (Interrupt Service Routine or just interrupt handler) it needs to change the pin configuration to detect interruption in the falling edge.

So at hcsr04_int_handler I did it:

if (priv->rising)
  /* Get the clock ticks from the free running timer */

  priv->time_start_pulse = priv->config->get_clock(priv->config);

  /* Now we need to wait for the falling edge interruption */

  priv->rising = false;
  priv->config->irq_setmode(priv->config, priv->rising);
  priv->config->irq_enable(priv->config, true);
  /* Get the clock ticks from the free running timer */

  priv->time_finish_pulse = priv->config->get_clock(priv->config);

  /* Disable interruptions */

  priv->config->irq_enable(priv->config, false);

  /* Convertion is done */


So now you got the idea how it works, we just need to understand the magic under the hood. These functions irq_enable(), irq_setmode(), get_clock(), etc, are in fact “function pointers” to board specific functions:

/* Interrupt configuration data structure */

struct hcsr04_config_s
  CODE int (*irq_attach)(FAR struct hcsr04_config_s * state, xcpt_t isr,
                         FAR void *arg);
  CODE void (*irq_enable)(FAR const struct hcsr04_config_s *state,
                          bool enable);
  CODE void (*irq_clear)(FAR const struct hcsr04_config_s *state);
  CODE void (*irq_setmode)(FAR struct hcsr04_config_s *state, bool risemode);
  CODE void (*set_trigger)(FAR const struct hcsr04_config_s *state, bool on);
  CODE int64_t (*get_clock)(FAR const struct hcsr04_config_s *state);

The real functions are at “nuttx/configs/stm32f103-minimum/src/stm32_hcsr04.c”

This way we can create a generic abstraction and let it work with any board/microcontroller.

As you probably already figured-out, it is the irq_setmode() function that defines if the GPIO pin (connected to Echo pin of HC-SR04 module) will detect rising edge signal or falling edge signal:

/* Setup the interruption mode: Rising or Falling */

static void hcsr04_irq_setmode(FAR struct hcsr04_config_s *state, bool rise_mode)
  FAR struct stm32_hcsr04config_s *priv =
  (FAR struct stm32_hcsr04config_s *)state;

  if (rise_mode)
      priv->rising = true;
      priv->falling = false;
      priv->rising = false;
      priv->falling = true;

Ok, we just need the “rising” variable to store the current edge mode, because the “falling” variable always will be the inverse. But let us to use both for didactic reason. Now irq_enable() just call stm32_gpiosetevent() passing these edge parameters and enabling it (passing the driver’s interrupt handler) or disabling it (passing a NULL).

/* Enable or disable the GPIO interrupt */

static void hcsr04_irq_enable(FAR const struct hcsr04_config_s *state, bool enable)
  FAR struct stm32_hcsr04config_s *priv =
                                   (FAR struct stm32_hcsr04config_s *)state;

  sinfo("%d\n", enable);

  (void)stm32_gpiosetevent(GPIO_HCSR04_INT, priv->rising, priv->falling, true,
                           enable ? priv->isr : NULL, priv->arg);

Finally the get_clock() just returns the current clock tick of a free running timer configured to run at 1 microsecond resolution. I just need to convert the value of returned “timespec” variable “ts” to microseconds, multiplying tv_sec by 1 million (1 second has 1000000 us) and dividing tv_nsec by 1000 (1us = 1000 ns), see:

/* Return the current Free Running clock tick */

static int64_t hcsr04_get_clock(FAR const struct hcsr04_config_s *state)
  /* Get the time from free running timer */

  stm32_freerun_counter(&g_freerun, &ts);

  /* Return time in microseconds */

  return ((ts.tv_sec * 1000000) + (ts.tv_nsec / 1000));

So, I think you got the idea how this driver works. It is was easy to implement. You can read the complete code here: “nuttx/drivers/sensors/hc_sr04.c

Testing LLVM LIBC++ on NuttX

Clone NuttX:

$ git clone

Clone NuttX’s Apps:

$ git clone

Clone libc++ for NuttX:

$ git clone

Install the libc++ on NuttX:

cd libcxx
$ ./ ../nuttx/
Installing LLVM/libcxx in the NuttX source tree
Installation suceeded

Modify the HelloXX example to use sstream:

$ cd ..
$ cd apps

Download 0001-Modify-helloxx-to-test-sstream.patch:

Apply it:

$ git am 0001-Modify-helloxx-to-test-sstream.patch

Add (l)gamma to NuttX and add helloxx example:

$ cd ..
$ cd nuttx

Download 0001-Add-gamma-and-lgamma.patch:

Apply it:

$ git am 0001-Add-gamma-and-lgamma.patch

Download 0001-Add-helloxx-C-example-to-STM32F4Discovery.patch:

Apply it:

$ git am 0001-Add-helloxx-C-example-to-STM32F4Discovery.patch

Configure NuttX to use the helloxx example:

$ cd tools
$ ./ stm32f4discovery/helloxx

Compile it:

$ cd ..
$ make

Flash it:

$ sudo openocd -f interface/stlink-v2.cfg -f target/stm32f4x.cfg -c init -c "reset halt" -c "flash write_image erase nuttx.bin 0x08000000"

Restart NuttX, you should see:

Hello World! 42                                                              
helloxx_main: Saying hello from the dynamically constructed instance         
CHelloWorld::HelloWorld: Hello, World!!                                      
Hello World! 42                                                              
helloxx_main: Saying hello from the instance constructed on the stack        
CHelloWorld::HelloWorld: Hello, World!! 
helloxx_main: Saying hello from the statically constructed instance
CHelloWorld::HelloWorld: Hello, World!! 

Using NuttX as a library

It is possible to use NuttX as library, then you don’t need to compile the source code all the time, just modify your application and link it against the NuttX library.

Here I will explain step-by-step how to do that.

I will consider that you just entered on nuttx/tools and executed the ./ to select your board and your application profile (here my application is called “hello” and CONFIG_USER_ENTRYPOINT=”hello_main”). Then now instead of executing “make” to compile the source code you should to execute:

make export

If everything worked as expected you will get the file “”. Extract this file and create your application inside it. Here I create a hello.c file with it:


int hello_main(void)
        printf("Hello World!\n");
        return 0;

Now I compiled it this way:

$ arm-none-eabi-gcc -c -fno-builtin -Wall -Wstrict-prototypes -Wshadow -Wundef -g -mcpu=cortex-m4 -mthumb -mfloat-abi=soft -I. -isystem ./include   -pipe -I "./include"  hello.c -o  hello.o

We just need to link again libnuttx.a to generate our nuttx ELF:

$ arm-none-eabi-ld --entry=__start -nostartfiles -nodefaultlibs -T./build/spificonfig.ld -L./libs hello.o -o nuttx.elf --start-group -lnuttx "/usr/lib/gcc/arm-none-eabi/6.2.1/thumb/v7e-m/libgcc.a" --end-group

And to generate the finaly binary from the ELF:

$ arm-none-eabi-objcopy -S -O binary nuttx.elf nuttx.bin

It is also a good idea to generate the map of symbols with the physical address of each function:

$ arm-none-eabi-nm nuttx.elf | \
grep -v '\(compiled\)\|\(\.o$\)\|\( [aUw] \)\|\(\.\.ng$\)\|\(LASH[RL]DI\)' | \
sort >

Well done, now just flash it using OpenOCD and STLink-V2 :

$ sudo openocd -f interface/stlink-v2.cfg -f target/lpc4330.cfg -c init -c "reset halt" -c "flash write_image erase nuttx.bin 0x14000000"
Open On-Chip Debugger 0.10.0 (2017-02-12-09:48)
Licensed under GNU GPL v2
For bug reports, read
Info : auto-selecting first available session transport "hla_swd". To override use 'transport select '.
adapter speed: 500 kHz
Info : The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD
Info : Unable to match requested speed 500 kHz, using 480 kHz
Info : Unable to match requested speed 500 kHz, using 480 kHz
Info : clock speed 480 kHz
Info : STLINK v2 JTAG v17 API v2 SWIM v4 VID 0x0483 PID 0x3748
Info : using stlink api v2
Info : Target voltage: 3.273164
Info : lpc4350.m4: hardware has 6 breakpoints, 4 watchpoints
target halted due to debug-request, current mode: Thread 
xPSR: 0x01000000 pc: 0x10402c40 msp: 0x10087ff0
auto erase enabled
Info : Found flash device 'win w25q64cv' (ID 0x001740ef)
Warn : no flash bank found for address 28000000
Warn : no flash bank found for address 280074c4
wrote 0 bytes from file nuttx.bin in 0.087209s (0.000 KiB/s)

Using LPCScrypt to flash firmware on Bambino board

I decided to use LPCScrypt from NXP to flash the Bambino-200E board. This way other people could to flash NuttX inside the board without a JTAG/SWD programmer, because LPCScrypt uses DFU to do that.

Initially I downloaded the LPCScrypt 1.8 for Linux from NXP site:

I read the documentation and installed the dependencies and support to run 32-bits application. But LPCScrypt installer was not starting:

$ ./lpcscrypt_1.8.0_723_Linux-x86 
invalid command name "bind"
    while executing
"::unknown bind Text "
    ("uplevel" body line 1)
    invoked from within
"uplevel 1 $next $args"
    (procedure "::obj::Unknown" line 3)
    invoked from within
"bind Text "
    (procedure "::InstallJammer::InitializeGui" line 19)
    invoked from within
"::InstallJammer::InitializeGui "
    (procedure "::InstallJammer::InitInstall" line 68)
    invoked from within
    (file "/installkitvfs/main.tcl" line 22457)

Fortunately Jim Wolfman from Smoothie project had the LPCScrypt as a tar ball, then I don’t need to install:

$ wget
$ tar xvf lpcscrypt.tgz

I need to create a udev rule to avoid the USB CDC/ACM port be used as modem:

$ sudo vi /etc/udev/rules.d/99-lpcscrypt.rules
SUBSYSTEM=="usb", ATTRS{idVendor}=="1fc9", ATTRS{idProduct}=="000c", MODE="0666"
SUBSYSTEM=="tty", ATTRS{idVendor}=="1fc9", ATTRS{idProduct}=="0083", MODE="0666"
ATTRS{idVendor}=="1fc9", ATTRS{idProduct}=="0083", ENV{ID_MM_DEVICE_IGNORE}="1"

Also you need to install the dfu-util program before using the lpcscrypt.

So, now jump/connect the two pins of BOOT (JP1) and reset the board. The board will enter on DFU mode, then you can execute the boot_lpcscrypt:

$ sudo ./lpcscrypt/scripts/boot_lpcscrypt

If the above command fails, you can try to run it manually:

$ sudo dfu-util -d 0x1fc9:0x000c -c 0 -i 0 -t 2048 -R  -D ./lpcscrypt/bin/LPCScrypt_140.bin.hdr

You can run dmesg to see if ttyACM0 was detected after running the LPCScrypt binary.

Finally you can run this command to flash nuttx.bin inside the external flash of Bambino board:

$ ./lpcscrypt/bin/lpcscrypt program -d /dev/ttyACM0 +c nuttx.bin SPIFI

That is it. I hope it works for you too.

Tips: SD Card Detection on NuttX

Today I got SDCard over SPI working on NuttX and already submitted the patch to mainline:

Now you also can test SDCard using the STM32F103-Minimum board.

This post is to explain how NuttX’s SDCard driver does to ignore the Card Detect pin on modules that doesn’t have it. Yes, my module doesn’t have CD pin, see:

Initially I was getting this warning message:

WARNING: No card present

And when I tried to mount the SDCard it reported error -19. Well, error -19 is “ENODEV”, that means: “No such device”.

Then analyzing the source code of the driver (at nuttx/drivers/mmcsd/mmcsd_spi.c) I found this:

  /* Check if there is a card present in the slot.  This is normally a matter is
   * of GPIO sensing and does not really involve SPI, but by putting this
   * functionality in the SPI interface, we encapsulate the SPI MMC/SD
   * interface

      fwarn("WARNING: No card present\n");
      slot->state |= MMCSD_SLOTSTATUS_NODISK;
      return -ENODEV;

Hmm, interesting! NuttX can use the return of spi_status() function to inform that card is present. Interesting, I was going to mess with the card detection thread/callback, saved by the bell!

Then all I did was to include:

  if (devid == SPIDEV_MMCSD)
       status |= SPI_STATUS_PRESENT;

inside the stm32_spi1status() at nuttx/configs/stm32f103-minimum/src/stm32_spi.c!

This is a simple and clever solution, like everything else in the NuttX!

NuttX 10 Years!

Tomorrow 07 Feb 2017 NuttX RTOS will complete 10 years as an Open Source project. The projects was published in the SourceForge on 07 Feb 2007.

From 2007 to 2017 NuttX evolved a lot. Maybe you don’t know, but NuttX is used by many companies. If you have a Moto Z Phone and got a Snap cover that Snap run NuttX!

Other example is Sony (that company that inspired Steve Jobs to create great products) is also using NuttX and even did a publish presentation about the benefits of using NuttX:

I discovered about NuttX in 2010. My friend Marcelo Barros pointed about an article in the Linux Jornal. Since then I have used NuttX in many projects as you can find on my old posts.

Also I created a YouTube channel dedicated to NuttX, called NuttX Channel:

NuttX is evolving fast and will be a Linux companion on “Embedded Arena”.

There is no other RTOS good like NuttX, you can spend your time searching. There are more than 200 available:

Thank Greg Nutt for this incredible RTOS called NuttX.

More here: