Writing your First Application

This topic explains how to create and run your first onboard application. It covers all the basic concepts and APIs required for app development on PX4.

:::note For simplicity, more advanced features like start/stop functionality and command-line arguments are omitted. These are covered in Application/Module Template. :::

Prerequisites

You will require the following:

The source code PX4-Autopilot/src/examples/px4_simple_app directory contains a completed version of this tutorial that you can review if you get stuck.

  • Rename (or delete) the px4_simple_app directory.

Minimal Application

In this section we create a minimal application that just prints out Hello Sky!. This consists of a single C file and a cmake definition (which tells the toolchain how to build the application).

  1. Create a new directory PX4-Autopilot/src/examples/px4_simple_app.

  2. Create a new C file in that directory named px4_simple_app.c:

    • Copy in the default header to the top of the page. This should be present in all contributed files!

      /****************************************************************************
       *
       *   Copyright (c) 2012-2022 PX4 Development Team. All rights reserved.
       *
       * Redistribution and use in source and binary forms, with or without
       * modification, are permitted provided that the following conditions
       * are met:
       *
       * 1. Redistributions of source code must retain the above copyright
       *    notice, this list of conditions and the following disclaimer.
       * 2. Redistributions in binary form must reproduce the above copyright
       *    notice, this list of conditions and the following disclaimer in
       *    the documentation and/or other materials provided with the
       *    distribution.
       * 3. Neither the name PX4 nor the names of its contributors may be
       *    used to endorse or promote products derived from this software
       *    without specific prior written permission.
       *
       * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
       * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
       * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
       * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
       * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
       * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
       * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
       * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
       * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
       * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
       * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
       * POSSIBILITY OF SUCH DAMAGE.
       *
       ****************************************************************************/
    • Copy the following code below the default header. This should be present in all contributed files!

      /**
       * @file px4_simple_app.c
       * Minimal application example for PX4 autopilot
       *
       * @author Example User <mail@example.com>
       */
      
      #include <px4_platform_common/log.h>
      
      __EXPORT int px4_simple_app_main(int argc, char *argv[]);
      
      int px4_simple_app_main(int argc, char *argv[])
      {
      	PX4_INFO("Hello Sky!");
      	return OK;
      }

      :::tip The main function must be named <module_name>_main and exported from the module as shown. :::

      :::tip PX4_INFO is the equivalent of printf for the PX4 shell (included from px4_platform_common/log.h). There are different log levels: PX4_INFO, PX4_WARN, PX4_ERR, PX4_DEBUG. Warnings and errors are additionally added to the ULog and shown on Flight Review. :::

  3. Create and open a new cmake definition file named CMakeLists.txt. Copy in the text below:

    ############################################################################
    #
    #   Copyright (c) 2015 PX4 Development Team. All rights reserved.
    #
    # Redistribution and use in source and binary forms, with or without
    # modification, are permitted provided that the following conditions
    # are met:
    #
    # 1. Redistributions of source code must retain the above copyright
    #    notice, this list of conditions and the following disclaimer.
    # 2. Redistributions in binary form must reproduce the above copyright
    #    notice, this list of conditions and the following disclaimer in
    #    the documentation and/or other materials provided with the
    #    distribution.
    # 3. Neither the name PX4 nor the names of its contributors may be
    #    used to endorse or promote products derived from this software
    #    without specific prior written permission.
    #
    # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
    # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
    # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
    # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
    # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
    # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
    # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
    # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
    # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    # POSSIBILITY OF SUCH DAMAGE.
    #
    ############################################################################
    px4_add_module(
    	MODULE examples__px4_simple_app
    	MAIN px4_simple_app
    	STACK_MAIN 2000
    	SRCS
    		px4_simple_app.c
    	DEPENDS
    	)

    The px4_add_module() method builds a static library from a module description.

    • The MODULE block is the Firmware-unique name of the module (by convention the module name is prefixed by parent directories back to src).

    • The MAIN block lists the entry point of the module, which registers the command with NuttX so that it can be called from the PX4 shell or SITL console.

    :::tip The px4_add_module() format is documented in PX4-Autopilot/cmake/px4_add_module.cmake. :::

    :::note If you specify DYNAMIC as an option to px4_add_module, a shared library is created instead of a static library on POSIX platforms (these can be loaded without having to recompile PX4, and shared to others as binaries rather than source code). Your app will not become a builtin command, but ends up in a separate file called examples__px4_simple_app.px4mod. You can then run your command by loading the file at runtime using the dyn command: dyn ./examples__px4_simple_app.px4mod :::

  4. Create and open a new Kconfig definition file named Kconfig and define your symbol for naming (see Kconfig naming convention). Copy in the text below:

     bool "PX4 Simple app"
     default n
     ---help---
     	Enable PX4 simple app

Build the Application/Firmware

The application is now complete. In order to run it you first need to make sure that it is built as part of PX4. Applications are added to the build/firmware in the appropriate board-level px4board file for your target:

To enable the compilation of the application into the firmware add the corresponding Kconfig key CONFIG_EXAMPLES_PX4_SIMPLE_APP=y in the px4board file or run boardconfig make px4_fmu-v4_default boardconfig:

:::note The line will already be present for most files, because the examples are included in firmware by default. :::

Build the example using the board-specific command:

  • jMAVSim Simulator: make px4_sitl_default jmavsim

  • Pixhawk v1/2: make px4_fmu-v2_default (or just make px4_fmu-v2)

  • Pixhawk v3: make px4_fmu-v4_default

  • Other boards: Building the Code

Test App (Hardware)

Upload the firmware to your board

Enable the uploader and then reset the board:

  • Pixhawk v1/2: make px4_fmu-v2_default upload

  • Pixhawk v3: make px4_fmu-v4_default upload

It should print before you reset the board a number of compile messages and at the end:

Once the board is reset, and uploads, it prints:

Connect the Console

Now connect to the system console either via serial or USB. Hitting ENTER will bring up the shell prompt:

Type ''help'' and hit ENTER

Note that px4_simple_app is now part of the available commands. Start it by typing px4_simple_app and ENTER:

The application is now correctly registered with the system and can be extended to actually perform useful tasks.

Test App (SITL)

If you're using SITL the PX4 console is automatically started (see Building the Code > First Build (Using the jMAVSim Simulator)). As with the nsh console (see previous section) you can type help to see the list of built-in apps.

Enter px4_simple_app to run the minimal app.

The application can now be extended to actually perform useful tasks.

Subscribing to Sensor Data

To do something useful, the application needs to subscribe inputs and publish outputs (e.g. motor or servo commands).

:::tip The benefits of the PX4 hardware abstraction comes into play here! There is no need to interact in any way with sensor drivers and no need to update your app if the board or sensors are updated. :::

Individual message channels between applications are called topics. For this tutorial, we are interested in the SensorCombined topic, which holds the synchronized sensor data of the complete system.

Subscribing to a topic is straightforward:

The sensor_sub_fd is a topic handle and can be used to very efficiently perform a blocking wait for new data. The current thread goes to sleep and is woken up automatically by the scheduler once new data is available, not consuming any CPU cycles while waiting. To do this, we use the poll() POSIX system call.

Adding poll() to the subscription looks like (pseudocode, look for the full implementation below):

Compile the app again by entering:

Testing the uORB Subscription

The final step is to start your application as a background process/task by typing the following in the nsh shell:

Your app will display 5 sensor values in the console and then exit:

:::tip The Module Template for Full Applications can be used to write background process that can be controlled from the command line. :::

Publishing Data

To use the calculated outputs, the next step is to publish the results. Below we show how to publish the attitude topic.

:::note We've chosen attitude because we know that the mavlink app forwards it to the ground control station - providing an easy way to look at the results. :::

The interface is pretty simple: initialize the struct of the topic to be published and advertise the topic:

In the main loop, publish the information whenever its ready:

Full Example Code

The complete example code is now:

Running the Complete Example

And finally run your app:

If you start QGroundControl, you can check the sensor values in the real time plot (Analyze > MAVLink Inspector).

Wrap-Up

This tutorial covered everything needed to develop a basic PX4 autopilot application. Keep in mind that the full list of uORB messages/topics is available here and that the headers are well documented and serve as reference.

Further information and troubleshooting/common pitfalls can be found here: uORB.

The next page presents a template for writing a full application with start and stop functionality.

Last updated