2. Publisher-Subscriber

2.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>.

2.1.1. Publisher node

listing/tutorial/talker.cpp

2.1.2. Subscriber Node

The listing/tutorial/listener.cpp

2.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>.

2.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)

2.1.5. Useful ROS commands

rosnode rostopic rosmsg