[Documentation] [TitleIndex] [WordIndex

Note: This tutorial assumes you have completed the writing a tf broadcaster tutorial (Python) (C++).
(!) Please ask about problems and questions regarding this tutorial on answers.ros.org. Don't forget to include in your question the link to this page, the versions of your OS & ROS, and also add appropriate tags.

Writing a tf listener (C++)

Description: This tutorial teaches you how to use tf to get access to frame transformations.

Tutorial Level: BEGINNER

Next Tutorial: Adding a frame (C++)

In the previous tutorials we created a tf broadcaster to publish the pose of a turtle to tf. In this tutorial we'll create a tf listener to start using tf.

How to create a tf listener

Let's first create the source files. Go to the package we created in the previous tutorial:

 $ roscd learning_tf

The Code

Fire up your favorite editor and paste the following code into a new file called src/turtle_tf_listener.cpp.

https://raw.github.com/ros/geometry_tutorials/groovy-devel/turtle_tf/src/turtle_tf_listener.cpp

   1 #include <ros/ros.h>
   2 #include <tf/transform_listener.h>
   3 #include <turtlesim/Velocity.h>
   4 #include <turtlesim/Spawn.h>
   5 
   6 int main(int argc, char** argv){
   7   ros::init(argc, argv, "my_tf_listener");
   8 
   9   ros::NodeHandle node;
  10 
  11   ros::service::waitForService("spawn");
  12   ros::ServiceClient add_turtle = 
  13     node.serviceClient<turtlesim::Spawn>("spawn");
  14   turtlesim::Spawn srv;
  15   add_turtle.call(srv);
  16 
  17   ros::Publisher turtle_vel = 
  18     node.advertise<turtlesim::Velocity>("turtle2/command_velocity", 10);
  19 
  20   tf::TransformListener listener;
  21 
  22   ros::Rate rate(10.0);
  23   while (node.ok()){
  24     tf::StampedTransform transform;
  25     try{
  26       listener.lookupTransform("/turtle2", "/turtle1",  
  27                                ros::Time(0), transform);
  28     }
  29     catch (tf::TransformException ex){
  30       ROS_ERROR("%s",ex.what());
  31       ros::Duration(1.0).sleep();
  32     }
  33 
  34     turtlesim::Velocity vel_msg;
  35     vel_msg.angular = 4.0 * atan2(transform.getOrigin().y(),
  36                                 transform.getOrigin().x());
  37     vel_msg.linear = 0.5 * sqrt(pow(transform.getOrigin().x(), 2) +
  38                                 pow(transform.getOrigin().y(), 2));
  39     turtle_vel.publish(vel_msg);
  40 
  41     rate.sleep();
  42   }
  43   return 0;
  44 };

It's important to note that the above code is essential to finish the tf tutorials and it will NOT compile on ROS Hydro, due to a slight change in the naming of certain messages and topics. The turtlesim/Velocity.h header is not used anymore, it has been replaced by geometry_msgs/Twist.h. Furthermore, the topic /turtle/command_velocity is now called /turtle/cmd_vel. In light of this, a few changes are necessary to make it work:

https://raw.github.com/ros/geometry_tutorials/hydro-devel/turtle_tf/src/turtle_tf_listener.cpp

   1 #include <ros/ros.h>
   2 #include <tf/transform_listener.h>
   3 #include <geometry_msgs/Twist.h>
   4 #include <turtlesim/Spawn.h>
   5 
   6 int main(int argc, char** argv){
   7   ros::init(argc, argv, "my_tf_listener");
   8 
   9   ros::NodeHandle node;
  10 
  11   ros::service::waitForService("spawn");
  12   ros::ServiceClient add_turtle =
  13     node.serviceClient<turtlesim::Spawn>("spawn");
  14   turtlesim::Spawn srv;
  15   add_turtle.call(srv);
  16 
  17   ros::Publisher turtle_vel =
  18     node.advertise<geometry_msgs::Twist>("turtle2/cmd_vel", 10);
  19 
  20   tf::TransformListener listener;
  21 
  22   ros::Rate rate(10.0);
  23   while (node.ok()){
  24     tf::StampedTransform transform;
  25     try{
  26       listener.lookupTransform("/turtle2", "/turtle1",
  27                                ros::Time(0), transform);
  28     }
  29     catch (tf::TransformException &ex) {
  30       ROS_ERROR("%s",ex.what());
  31       ros::Duration(1.0).sleep();
  32       continue;
  33     }
  34 
  35     geometry_msgs::Twist vel_msg;
  36     vel_msg.angular.z = 4.0 * atan2(transform.getOrigin().y(),
  37                                     transform.getOrigin().x());
  38     vel_msg.linear.x = 0.5 * sqrt(pow(transform.getOrigin().x(), 2) +
  39                                   pow(transform.getOrigin().y(), 2));
  40     turtle_vel.publish(vel_msg);
  41 
  42     rate.sleep();
  43   }
  44   return 0;
  45 };

If you get an error "Lookup would require extrapolation into the past" while running, you can try this alternative code to call the listener:

try {
    listener.waitForTransform(destination_frame, original_frame, ros::Time(0), ros::Duration(10.0) );
    listener.lookupTransform(destination_frame, original_frame, ros::Time(0), transform);
} catch (tf::TransformException ex) {
    ROS_ERROR("%s",ex.what());
}

The Code Explained

Now, let's take a look at the code that is relevant to publishing the turtle pose to tf.

   2 #include <tf/transform_listener.h>
   3 

The tf package provides an implementation of a TransformListener to help make the task of receiving transforms easier. To use the TransformListener, we need to include the tf/transform_listener.h header file.

  20   tf::TransformListener listener;

Here, we create a TransformListener object. Once the listener is created, it starts receiving tf transformations over the wire, and buffers them for up to 10 seconds. The TransformListener object should be scoped to persist otherwise it's cache will be unable to fill and almost every query will fail. A common method is to make the TransformListener object a member variable of a class.

  25     try{
  26       listener.lookupTransform("/turtle2", "/turtle1",
  27                                ros::Time(0), transform);
  28     }

Here, the real work is done, we query the listener for a specific transformation. Let's take a look at the four arguments:

  1. We want the transform from frame /turtle1 to frame /turtle2.
  2. The time at which we want to transform. Providing ros::Time(0) will just get us the latest available transform.

  3. The object in which we store the resulting transform.

All this is wrapped in a try-catch block to catch possible exceptions.

  35     geometry_msgs::Twist vel_msg;
  36     vel_msg.angular.z = 4.0 * atan2(transform.getOrigin().y(),
  37                                     transform.getOrigin().x());
  38     vel_msg.linear.x = 0.5 * sqrt(pow(transform.getOrigin().x(), 2) +

Here, the transform is used to calculate new linear and angular velocities for turtle2, based on its distance and angle from turtle1. The new velocity is published in the topic "turtle2/cmd_vel" and the sim will use that to update turtle2's movement.

Running the listener

Now that we created the code, lets compile it first. Open the CMakeLists.txt file, and add the following line on the bottom:

add_executable(turtle_tf_listener src/turtle_tf_listener.cpp)
target_link_libraries(turtle_tf_listener ${catkin_LIBRARIES})

Build your package at the top folder of your catkin workspace:

  $ catkin_make

If everything went well, you should have a binary file called turtle_tf_listener in your devel/lib/learning_tf folder.

  rosbuild_add_executable(turtle_tf_listener src/turtle_tf_listener.cpp)

Build your package:

  $ make

If everything went well, you should have a binary file called turtle_tf_listener in your bin folder.

If so, we're ready add it the launch file for this demo. With your text editor, open the launch file called start_demo.launch, and merge the node block below inside the <launch> block:

  <launch>
    ...
    <node pkg="learning_tf" type="turtle_tf_listener"
          name="listener" />
  </launch>

First, make sure you stopped the launch file from the previous tutorial (use ctrl-c). Now you're ready to start your full turtle demo:

 $ roslaunch learning_tf start_demo.launch

You should see the turtlesim with two turtles.

Checking the results

To see if things work, simply drive around the first turtle using the arrow keys (make sure your terminal window is active, not your simulator window), and you'll see the second turtle following the first one!

When the turtlesim starts up you may see:

This happens because our listener is trying to compute the transform before messages about turtle 2 have been received because it takes a little time to spawn in turtlesim and start broadcasting a tf frame.

Now you're ready to move on to the next tutorial, where you'll learn how to add a frame (Python) (C++)


2018-08-18 13:23