Start Coding on ROS

how to Start Coding on ROS

Written by Ricardo Tellez

30/09/2019

In order to create ROS programs, you will need a C++ or Python code editor. In this chapter, we are going to show you a list of integrated environments for programming ROS with those languages. Many others do exist, but we are putting the most complete and easy to start with ones here.

Note: since ROS only works on Linux (at least at present), all the IDEs included here are Linux environments, even if Windows versions may exist.

If you don’t already know Linux, here’s a free course for getting started: Linux for Robotics

What follows is a description of two of the best editors for each language. The rest of the information in this chapter has been copied from wiki.ros.org. We are putting it here for your convenience.

CLOUD IDES

Using the ROS Development Studio as your IDE

You can simplify your life when working with ROS by using the ROS Development StudioThe ROSDS comes off-the-shelf with ROS, Gazebo, and IDE already installed. You need no installation on your computer, just a web browser. The main advantage of the ROSDS is that it allows you to develop on ANY operating system. It also allows programming in both C++ or Python with autocomplete functionality.

Additionally, ROSDS provides running simulations of the robots, so you can quickly test your programs in realistic simulations of robots and check that your program is actually doing what it is supposed to do. This is a very important step while developing for robots (as you will see in the next chapter). You have a full set of tutorials about how to use ROSDS here.

ROSDS allows you to share your already-working ROS projects with your peers with a single click. By sharing your projects, your mates will receive an exact copy of what you shared. This implies that your peers will be able to run it the exact same way as you. This is interesting for replicating research results, for providing exercises to students, for robot competitions based on simulations, or for just sharing code with non-experts.

Finally, let us mention that ROSDS can deploy into your real robot. You can switch from testing in the simulation to running in the robot with a couple of clicks.
If you choose to use the ROSDS, then you can skip the rest of this chapter.

ROS Development Studio developing a reinforcement learning ROS program for Fetch

ROS Development Studio developing a reinforcement learning ROS program for Fetch

LOCAL IDES

What follows is a list of some of the best editors for each language (Python and C++) that you can install on your local computer.

Eclipse

CLion

NetBeans

QTCreator

PyCharm

Visual Studio Code

IDES FOR PYTHON

Here we introduce you two of the Python environments used by our team.

*If you are lacking in Python, in this free course you will learn the basics of Python for robot programming: Python for Robotics.

1. NETBEANS

Installing NetBeans

Although NetBeans is included in Ubuntu repositories, everything described here was tested with NetBeans 6.9.1.

$ sudo sh netbeans-6.9.1-ml-cpp-linux.sh

Getting ROS environment variables in NetBeans

NetBeans can “import” project from existing sources. It can use Makefiles, and even run configure script or CMake to generate one. But, that kind of automatic project configuration and build would overwrite stub makefile that every ROS package has. That makefile in essence runs ROS build system for a package, and that is what we want NetBeans to do.

In order to use rosmake from NetBeans, we need to set ROS environment variables in NetBeans. Since NetBeans is started with a shell script on Linux, we can include the variables in the script.

Since from recent versions rosinstall generates setup.sh, setup.bash and setup.zsh (as opposed to just setup.sh which was actually a bash script), there is no need for all the steps that are described in the next section.

The following will suffice to get ROS environment variables to NetBeans:

$ roscd
$ cd ..
$ echo ". $(pwd)/setup.sh" > ~/.netbeans/6.9/etc/netbeans.conf

We don’t actually need perks specific to bash.

The exact path of netbeans.conf for the various OS can be found here: http://wiki.netbeans.org/FaqNetbeansConf

Making NetBeans project

We’ll try to set up project for Microstrain 3DM-GX2 IMU driver package, so note it’s path:

$ roscd microstrain_3dmgx2_imu
$ pwd
  • Start “C/C++ Project with Existing Sources” wizard
  • Use the above path to “Specify the folder that contains existing sources”
  • Select “Custom” Configuration Mode (note that Automatic Mode recognizes cmake)
  • Proceed with the wizard accepting defaults

You should get a NetBeans project for microstrain_3dmgx2_imu package with automatically configured Code Assistance (and almost working for all dependencies). E.g. you can see that the bullet library headers weren’t parsed.

We will configure Code Assistance manually. That means entering paths to all header files the package uses and all preprocessor definitions.

To get the paths to include files for the package we will use rospack. Further, we’ll use sed to format them for easier input to NetBeans.

$ rospack cflags-only-I microstrain_3dmgx2_imu | sed 's/ /:/g'-

Open the project properties. Go to Code Assistance -> C++ Compiler and paste the output of the above command to Include Directories field.

Use rospack to find the preprocessor definitions and enter them manually.

$ rospack cflags-only-other microstrain_3dmgx2_imu

Code auto-formatting in NetBeans

The following file netbeans-ros-code_style.zip is prepared to enable auto-formatting of C++ code in NetBeans as defined in CppStyleGuide. In order to use it, you should import it to Netbeans (Tools -> Options -> Import).

With this, the example given in CppStyleGuide#Formatting will be identically formatted, except for extra blank lines before function or class definitions. For a discussion see Google C++ style guide Vertical Whitespace.

2. PYCHARM

PyCharm is an IDE for Python. In order to run and debug ROS functionality, you need to modify the desktop file for PyCharm (the same procedure as for other IDE’s). In Ubuntu 16.04 (and possibly earlier versions), you can edit the launcher file in either /usr/share/ applications or ~/.local/share/applications (depending on whether or not you installed PyCharm for all users). The launcher file may be called pycharm-community.desktop or jetbrains-pycharm- ce.desktop. Change the line that reads

Exec="/usr/lib/pycharm-community/bin/pycharm.sh" %f

by adding bash -i -c at the beginning:

Exec=bash -i -c "/usr/lib/pycharm-community/bin/pycharm.sh" %f

Packages

In order to work with packages just create a new project in the parent folder for all your packages or in a particular package. Please note that folder .idea with project files will be created. You can add it to .gitignore file in case if you are using Git and do not want to commit this file to repository. PyCharm will parse all files in the packages and allow you quick navigation, fast code completions, run and debug Python code, unitest run and debug.

Code

Code can be run using roslaunch or rosrun command from the command line. Simple Python files can be run using run context menu.

In order to debug Python node do the following changes:

  • Comment node in the launch file my_nodes.launch
  • If the node has any parameters specified inside put them into <group> tag with ns attribute equal to node name
  • Launch my_nodes.launch using roslaunch command
  • Run Python node from PyCharm IDE in debug mode

Unittest

Unittest can be simply run using content menu on the file in the project tree or on a particular method in the code. Results would be shown in UI.

Unittest can be normally debug using start debug menu. In case of integration test (rostest):

  • Comment <test> tag in the my_file.test launch file
  • launch my_file.test using roslaunch not rostest
  • launch test using PyCharm unittest debug from IDE

Custom Messages/Services

Define and build your messages/services as usual. In order Pycharm to recognize them (for autocompletion, etc.):

  • Open File – Settings
  • Select Project: projectname – Project Structure
  • Select src folder and click on Mark as Sources
  • Click OK

IDES FOR C++

1. Eclipse

Eclipse’s built-in C++ indexing capabilities have gotten quite good in recent versions.

Installing Eclipse

To use this tutorial, users should not “sudo apt-get install eclipse”. Instead:

  • Go to eclipse web site
  • Click on “download now” from the top-right corner
  • Download eclipse for C/C++ developers
  • Extract eclipse into a folder of your choice

To make a nice launcher for Ubuntu, google for instructions or check e.g. http://www.blogs.digitalworlds.net/softwarenotes/?p=54

Creating the Eclipse project files

1. For a rosbuild package

CMake can produce Eclipse project files automatically. These project files then set up all include paths correctly, so that auto-completion and code browsing will work out of the box.

However, currently, a small hack is required for generating these project files in the right folder. The problem is that ROS creates the Makefiles and all other build artifacts in the build/ folder, but Eclipse expects the source files to be located within (or below) the folder where its project files are stored.

Fortunately, there is now a make target using a small script that circumvents this problem, by forcing CMake to create the project files in the directory of your package (and not the build/ folder). Proceed as follows:

  • Open a terminal, roscd into the folder of your package, and execute:make eclipse-project
  • You will now find two Eclipse files in your package. It is not recommended to add them to the repository, as they contain absolute links and will be different for different users checking out your software.
  • Note that if you change anything to your manifest.xml, you will have to run this script again, which will overwrite your Eclipse project file and thereby reverting all manual changes to the project settings.

Note: Simply running the cmake Eclipse generator like

cmake -G"Eclipse CDT4 - Unix Makefiles"

will overwrite the Makefile. This can also happen if make eclipse-project does not complete successfully. If you already did this, you will want to restore the original Makefile, which should contain the following line:

include $(shell rospack find mk)/cmake.mk
2. Creating eclipse files for multiple packages/stacks

Go to the directory where your packages reside (which may be a stack-folder or just a simple folder) and run:

rosmake --target=eclipse-project --specified-only *

If you need to convert deeper nested packages or multiple stacks at once be encouraged to use this eclipse projects bash script (https://gist.github.com/1098960) for subdirectories.

3. Catkin-y approach

If you are using catkin, you do not have the possibility to use make eclipse-project. You need to execute:

catkin_make --force-cmake -G"Eclipse CDT4 - Unix Makefiles"

to generate the .project file and then run:

awk -f $(rospack find mk)/eclipse.awk build/.project > build/.project_with_env &amp;&amp; mv build/.project_with_env build/.project

to pass the current shell environment into the make process in Eclipse.

After executing this command you will find the project files in the build/ folder. Now you can import your project as an existing project into the workspace.

Maybe you will need to execute the following if you would like to debug your program. To execute this command cd to the build/ folder. You should do so if you e.g. get an error like “No source available for main()”.

cmake ../src -DCMAKE_BUILD_TYPE=Debug

For information on the proper approach using catkin, start here http://answers.ros.org/question/52013/catkin-and-eclipse/.


4. Catkin and Python

For me, the above procedure didn’t generate a .pydevproject file, like make eclipse-project ever did. Clicking Set as PyDev Project would create a config but without any Paths, so coding would be a hassle.

Workaround: From within the package you want to program run:

python $(rospack find mk)/make_pydev_project.py

Now copy the created file .pydevproject (which has all dependency package paths included) to /build and import your catkin-project into eclipse or set it as PyDev Project if already imported.

5. catkin tools

With the new catkin_tools, there are few changed from the Catkin-y method described above. To generate eclipse-project you need to execute:

$ catkin build --force-cmake -G"Eclipse CDT4 - Unix Makefiles"

to generate the .project files for each package and then run: the following script

$ ROOT=$PWD
$ cd build
$ for PROJECT in `find $PWD -name .project`; do

DIR=`dirname $PROJECT`
echo $DIR
cd $DIR
awk -f $(rospack find mk)/eclipse.awk .project > .project_with_env &amp;&amp; mv .project_with_env .project

$ done
$ cd $ROOT

To debug use the following command and you can mention the name of the package to configure that specific project for debug instead of the entire workspace. Remember to run the script to modify .project to pass the current shell environment into the make process in Eclipse.

$ catkin build --force-cmake -G"Eclipse CDT4 - Unix Makefiles" - DCMAKE_BUILD_TYPE=Debug
6. Importing the project into Eclipse

Now start Eclipse, select File –> Import –> Existing projects into workspace, hit next, then browse for your package’s directory (select root directory). Do NOT select Copy projects into workspace. Then finish.

You should now be able to browse through the code (hold down CTRL while clicking on a function/class name), get auto-completion (automatically appears, or press CTRL-SPACE) et cetera.

7. Fixing unresolved includes

There are many possible reasons why indexing cannot resolve all includes, functions, methods, variables, etc. Often, fixing the resolving of includes solves these errors. If you have any problems, these might be fixed by:

  • If the dependencies of your project have changed since first adding them to Eclipse, regenerate the project files and reimport the project into your workspace.
  • Making sure to load your .bashrc environment with Eclipse, by launching it using bash -i – c “eclipse” (see Reusing your shell’s environment).
  • In Eclipse, right-click the project, click properties -> C/C++ general -> Preprocessor Include Paths, Macros etc. Click the tab “Providers” and check the box next to “CDT GCC Built-in Compiler Settings [ Shared ]”.
  • Afterward, right-click the project, select Index -> Rebuild. This will rebuild your index. Once this is done, usually all includes will resolve.
  • As a last resort, you can also manually add folders that will be searched for headers, using right-click project -> properties -> C/C++ Include Paths and Symbols. This is usually not necessary though.
8. Building the project inside Eclipse

The eclipse-project makes the target automatically tries to set the environment variables correctly such that building within Eclipse should work out-of-the-box. Especially if you follow Reusing your shell’s environment from above.

If not, this is where you need to start looking: Right-click on the project, select Properties — > C/C++ Make Project –> Environment, and check whether the following environment variables are assigned to the correct values:

ROS_ROOT
ROS_PACKAGE_PATH
PYTHONPATH
PATH

The easiest way to obtain the correct values for your installation is to open a terminal and run

$ echo $ROS_ROOT
$ echo $ROS_PACKAGE_PATH
$ echo $PYTHONPATH
$ echo $PATH

You should now be able to compile your package properly, for example by hitting CTRL-B (or selecting Project –> Build project in the menu).

Note: When working with multiple projects, Eclipse won’t be able to determine the correct build order or when dependent projects have to be rebuilt. You have to set the project interdependencies manually for each project in your workspace (see http://help.eclipse.org/helios/index.jsp?topic=/org.eclipse.cdt.doc.user/reference/cdt_u_prop_general_pns_ref.htm).

9. Running and debugging your executables within Eclipse

As for building within Eclipse, the crucial step here is to set the required environment variables correctly in the launch configuration. As the same for building, this should work out-of-the-box, especially if you follow Reusing your shell’s environment from above.

Create a new launch configuration, right-click on the project, select Run –> Run configurations… –> C/C++ Application (double click or click on New). Select the correct binary on the main tab (Search project should work when your binary was already built). Then in the environment tab, add (at least)

ROS_ROOT
ROS_MASTER_URI

again with the values of your installation. If you are unsure about them, open a terminal and run

$ echo $ROS_ROOT

$ echo $ROS_MASTER_URI

Finally, if you cannot save the configuration, remove the @ character in the name of the new run configuration.

This should now allow you to run and debug your programs within Eclipse. The output directly goes into the Console of Eclipse. Note that the ROS_INFO macros use ANSI escape sequences, which are not parsed by Eclipse; therefore, the output might look similar to this one (from Writing a Publisher/Subscriber (C++)):

[0m[ INFO] [1276011369.925053237]: I published [Hello there! This is message [0]][0m

[0m[ INFO] [1276011370.125082573]: I published [Hello there! This is message [1]][0m

[0m[ INFO] [1276011370.325025148]: I published [Hello there! This is message [2]][0m

[0m[ INFO] [1276011370.525034947]: I published [Hello there! This is message [3]][0m

You could use an ANSI console plugin (e.g. http://www.mihai-nita.net/eclipse/) to get rid of the “[0m” characters in the output.

10. More eclipse goodies

Setup a file template that pre-formats whenever a new source or header file is created. The template could, for example, contain the license header, author name, and include guards (in case of a header file). To set up the templates, choose in the Preferences C/C++->Code Style->Code Templates. For example, to add the license header choose Files->C++ Source File->Default C++ source template and click on Edit… Paste the license header and click OK. From now on, all source files while automatically contain the license header.

Enable Doxygen with the project properties clicking on C/C++ General, enabling project-specific settings and selecting Doxygen as Documentation tool. This option automatically completes Doxygen style comments highlights them.

People that are used to the emacs key bindings can select emacs-style bindings in Windows- >Preferences General->Keys and selecting the emacs Scheme. Also, other useful key bindings (e.g. make project) can easily be added.

To also index files that live outside the ROS tree (e.g. the boost include files) you can add them in project properties C/C++ General->Paths and Symbols.

The generated eclipse project also works great for Python code. Just install the PyDev plugin for syntax highlighting and code completion.

11. Auto Formatting

Eclipse also has extensive formatting configuration capabilities. To add the ROS formatting profile to Eclipse, perform the following steps:

  • Download ROS_Format.xml to some location (versions: Indigo Kepler)
  • Start Eclipse
  • Select Window->Preferences->C/C++->Code Style
  • Click Import…
  • Select ROS_format.xml from the location used in step 1
  • Click OK

As you edit a file, Eclipse should use this new profile to format your code following the ROS conventions. To reformat an entire file, select Edit->Format.

2. QTCreator

As QtCreator supports opening CMake projects out of the box, it does not require a setup procedure if started from a terminal. Note that this is absolutely crucial because otherwise the environment will not be set correctly and functionality related to rosbuild or catkin will fail when running cmake.

Note that instead of starting QtCreator from a terminal, you can use the following modification to the desktop file which normally in Ubuntu resides in /usr/share/ applications if you did a system-wide installation or in ~/.local/share/applications if you installed it only for your user:

$ cat qtcreator.desktop [Desktop Entry]
Exec=bash -i -c qtcreator %F
Icon=qtcreator
Type=Application
Terminal=false
Name=Qt Creator
GenericName=Integrated Development Environment
MimeType=text/x-c++src;text/x-c++hdr;text/x-xsrc;application/x-designer;application/ vnd.nokia.qt.qmakeprofile;application/vnd.nokia.xml.qt.resource;
Categories=Qt;Development;IDE;
InitialPreference=9

In Ubuntu 13.04 and later, the third line must read:

Icon=QtProject-qtcreator

You should not try to generate this file yourself, but rather modify the file that was created when you installed QtCreator. Add bash -i -c in the Exec line and use it in your launcher. This will run your QtCreator in a shell which should source all required setup.bash files of your ROS installation and workspace. More about desktop files and their locations for Ubuntu can be found here. Note also that the same trick can be used with eclipse.

If you are experiencing issues with the qtcreator package shipped by Ubuntu (or want to use a more up to date version of QtCreator) when opening the CMakeLists, then try installing QtCreator from Nokia’s installer.

1. catkin_make

To open a catkin code as a project, use “Open File or Project” and select the top-level CMakeLists.txt of the catkin workspace (e.g. “catkin_ws/src/CMakeLists.txt“). Select the catkin build folder (e.g. “catkin_ws/build“) as the build directory and ‘Run CMake‘ (in order to enable debugging add following line into arguments edit box:

-DCMAKE_BUILD_TYPE=Debug).

Recently this has started to fail with errors like “CMake Error: The source directory “/opt/ ros/lunar/share/catkin/cmake” does not appear to contain CMakeLists.txt.”, because the main CMakeLists is a symlink to a non-writable location. The workaround is to make a copy of toplevel.cmake instead of using a symlink:

mv CMakeLists.txt CMakeLists.txt.old

cp /opt/ros/lunar/share/catkin/cmake/toplevel.cmake CMakeLists.txt

To be able to modify all the files in the workspace add those lines in “src/CMakeLists.txt” :

#Add custom (non compiling) targets so launch scripts and python files show up in QT Creator's project view.

file(GLOB_RECURSE EXTRA_FILES */*)

add_custom_target(${PROJECT_NAME}_OTHER_FILES ALL WORKING_DIRECTORY $ {PROJECT_SOURCE_DIR} SOURCES ${EXTRA_FILES})

If you want the project to be named something else than “Project” then add a line at the top with project(!MyProjectName).

You may specify the correct catkin devel and install spaces at Projects->Build Settings by providing the following CMake arguments:

 -DCATKIN_DEVEL_PREFIX=../devel – DCMAKE_INSTALL_PREFIX=../install
2. catkin tools

With the new catkin_tools, there is no longer a top-level make file for the whole workspace. Instead, open each package as an individual project in QtCreator. Make sure, that the build folder is set to ws/build/your_package instead of ws/build.

Before opening a package with QtCreator, though, make sure to build the package once with catkin build. If your build artifacts (binaries, libraries, …) end up in the wrong directory, you built the package first with QtCreator. You can check, whether you have this problem by simply doing a rosrun of your package’s node, change code, recompile with QtCreator and do a rosrun again — if you don’t see your changes in the executable’s behavior, it is probably installed into the wrong directory. To resolve this issue, just clean the package (catkin clean <pkg> for linked layout, for newer catkins, remove the build/<pkg> folder) and rebuild it with catkin build.

With QtCreator of version 4 and higher, you can (and actually have to) configure your compiler etc. in a Kit.

  • Go to Tools — Options — Build & Run — Kits. In the Default kit (or create a new kit for ROS)
  • Select the compiler you want to use in catkin
  • Select CodeBlocks — Unix Makfiles
  • Change the CMake Configuration to only contain QT_QMAKE_EXECUTABLE:STRING=%{Qt:qmakeExecutable} (i.e. remove the define for CMAKE_CXX_COMPILER)
  • In your workspace, execute
catkin config --cmake-args -DCMAKE_CXX_COMPILER:STRING=/usr/bin/g++ --

where you substitute /usr/bin/g++ with the compiler you actually want to use (and which is the same that you selected in the kit above). See this discussion about this issue.

You can configure some default paths in QtCreator:

The default build path (what you normally have to set manually once you open a new project): In Tools — Options — Build & Run — General set the Default build directory to

%{Env:CURRENT_CMAKE_BUILD_DIR}/%{CurrentProject:Name}

and in your ~/.bashrc (or ~/.zshrc`) add a line similar to

export CURRENT_CMAKE_BUILD_DIR="$(catkin locate --workspace ~/workspace --build)"

to define the variable CURRENT_CMAKE_BUILD_DIR.

The path in which to look for projects (i.e. where to start the search when you want to open a new project): Tools — Options — Build & Run — General — Projects directory set Directory to /home//workspace/src (or wherever your workspace is).

3. Enable Clang Code Model

Install recent clang (version >= 3.6) and this plugin. See the link for how to enable it. Although this may slow down your computer it is a very valuable tool to give you compiler warnings on-line.

4. Troubleshooting

When running cmake in QtCreator (when you open the package), check the output for error messages — they provide a clue on what is going wrong.

To remove cached/stored information for a project, remove the CMakeLists.txt.user (possibly with some trailing numbers) in your project and re-open the project. If that does not solve your problem, repeat (remove CMakeLists.txt.user) and additionally remove (or rather rename) the QtCreator configuration in ~/.config/QtProject and ~/.local/share/ data/QtProject/qtcreator and try again.

5. Qt Creator Plugin for ROS

Please refer to instructions here. https://ros-industrial.github.io/ros_qtc_plugin/

Related courses:

Topics:
Masterclass 2023 batch2 blog banner

Check Out These Related Posts

129. ros2ai

129. ros2ai

I would like to dedicate this episode to all the ROS Developers who believe that ChatGPT or...

read more

9 Comments

  1. kurt

    gusto ko

    Reply
  2. Jayson dela cruz

    Mabolo tuklas purok 5

    Reply
  3. Mark jayson dela cruz

    Mabolo tuklas purok 5

    Reply
  4. Isma

    Hi ROS pls gift me diamond 10 because i dont have any diamond and i know to top up in ros

    Reply
  5. Anonymous

    My ID 180741004

    Reply

Submit a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Pin It on Pinterest

Share This