4. Publisher-Subscriber

In ROS processes that are called nodes communicate with each others using topics. The are other ways to communicate that we will see in other chapters. Nodes sends messages over topics. The node that send a messages is called publisher. The one that is receiving is called subscriber.

In the workspace create a package called

catkin_create_pkg first_steps roscpp rospy std_msgs
cd first_steps
mkdir scripts

4.1. Simple Publisher-Subscriber ROS program

In this section we will make a package that contain 2 nodes. A publisher node (talker.cpp) and a subscriber node (listener.cpp). These two source files should be created in the src folder of the package.

Append to the CMakeLists.txt of the package the following:

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

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

This will create two executables, talker and listener, which by default will go into package directory of your devel space, located by default at ~/catkin_ws/devel/lib/<package name>.

4.1.1. Publisher node

4.1.2. Subscriber Node

4.1.3. Building nodes

Packages should be stored in workspace, if no work space is present, one should be created. The following steps should be done:

  • Create and build a workspace
  • Source the package environment variable
  • Create a package
  • Copy or create node source file into the src folder of the package
  • Eventually create new messages and services
  • Add nodes, messages and services to the CMakeLists.txt of the package
  • Build the workspace

Listing.ref{lstquickROS} show steps necessary to create in the home directory a workspace named catkin_ws, create a package called first_tutorial, and create two nodes in that package then build the workspace.

label=lstquickROS listing/tutorial/quickROS

This will create two executables, talker and listener, which by default will go into package directory of your devel space, located by default at ~/catkin_ws/devel/lib/<package name>.

4.1.4. Run nodes

roscore

rosrun beginner_tutorials talker      (C++)
rosrun beginner_tutorials talker.py   (Python)
rosrun beginner_tutorials listener     (C++)
rosrun beginner_tutorials listener.py  (Python)

4.1.5. Useful ROS commands

rosnode rostopic rosmsg