ROS2: Optimizing URDF model using XACRO

Optimizing URDF model using XACRO


This is an introductory chapter, explaining macros we are going to use.

In the URDF model that we are going to create, all wheels share shape and material properties. Links (URDF term for "objects") of the wheels have a lot in common, as well as joints (URDF term for things that connect objects together).

We can move repeating properties to a separate place (macro) to make our code better structured.

A XACRO file is an XML file. As its name implies, xacro is an Xml Macro. The xacro utility program runs all of the macros and outputs the result, producing a single file, in a way similar to what a preprocessor does to the include files and macros. Typical usage looks something like this:

                    $ xacro model.xacro > model.urdf

You can also automatically generate the urdf in a launch file.

                    path_to_urdf = get_package_share_path('pr2_description') / 'robots' / 'pr2.urdf.xacro'
                    robot_state_publisher_node = launch_ros.actions.Node(
                            'robot_description': ParameterValue(
                                Command(['xacro ', str(path_to_urdf)]), value_type=str

At the top of the URDF file, you must specify a namespace in order for the file to parse properly. For example, these are the first two lines of a valid xacro file:


Variables and macros

A minimal XACRO file looks like this:


Let's define some variables (constants) in XACRO. These are defined as , with a name and value attribute. The variable names need to use underscores instead of hyphens.


In addition to the variables, we can introduce Macros (using these variables):


It is possible to use complex expressions using the four basic operations (+,-,*,/), the unary minus, and parenthesis. Examples:


Macros are templates: to instantiate them, we use template name and necessary attributes:


Running XACRO from the Command Line

XACRO files can be manually rendered via the command line.

                    $ xacro src/fwd_bot/urdf/bot.xacro

Complete URDF example

Here is a sample bot.xacro file:


Additionally, we can store macros in a separate bot.xacro file, and use bot.urdf.xacro as a main file:





I am going to use the first approach (everything in one file) for now, as our robot is not that complex.

(C), all rights reserved

Please read the disclaimer