Writing a Simple Publisher and Subscriber (C++)

From Lofaro Lab Wiki
Jump to: navigation, search

Writing a Simple Publisher and Subscriber (C++)

1) In a terminal, move to your beginner_tutorials folder:

  cd ~/catkin_ws/src/beginner_tutorials 

Note: If you have a ~/catkin_ws/beginner_tutorials folder:

All changes that are done to the ~/catkin_ws/src/beginner_tutorials MUST be completed for ~/catkin_ws/beginner_tutorials as well.

2) In ~/catkin_ws/beginner_tutorials, remove all folders and files. This can be done manually using Home Folder.

3) Run:

  
cd ~/catkin_ws
catkin_create_pkg beginner_tutorials std_msgs rospy roscpp

If errors such as "File already exist" show up, delete those files from ~/catkin_ws/src/beginner_tutorials

Writing the Publisher Node

1) Create the file talker.cpp:

  gedit src/talker.cpp

2) In the gedit editor, paste all from this link. Save the file and close the editor. For information on what is inside this file, see this link. In a nutshell, it initializes the ROS system, advertise what we are doing, and finally loop what we are doing.

Writing the Subscriber Node

1) In a terminal, move to your beginner_tutorials folder:

  cd ~/catkin_ws/src/beginner_tutorials 

2) Create the file listener.cpp:

  gedit src/listener.cpp

3) In the gedit editor, paste all from this link. Save the file and close the editor. For information on what is inside this file, see this link. In a nutshell, it initializes the ROS system, subscribes to the topic 'chatter', spin (wait for messages), when message arrives call the chatterCallback() function.

Building Nodes 1) Run:

  catkin_create_pkg beginner_tutorials std_msgs rospy roscpp

This creates a CMakeLists.txt file and a Package.xml file. If there are errors such as "File does not exist", likely the cpp files created above need to be in the both of the beginner_tutorials folder.

2) Edit the CMakeList.txt file (this step should be just the one folder):

  gedit beginner_tutorials/CMakeLists.txt

Add the following to the end of the file:

  
include_directories(include ${catkin_INCLUDE_DIRS})

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

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

For a completely clean file, you can view the entire CMakeLists.txt file here

Save the file and close the editor. This should create a talker and listener files in your devel folder.

3) Navigate to your catkin workspace:

  cd ~/catkin_ws

4) And make the catkin:

  catkin_make