Skip to content

Publisher Subscriber Example

Chandra Gummaluru edited this page Feb 2, 2020 · 10 revisions

Publisher/Subscriber Example

In this part of the tutorial, we provide a step-by-step walkthrough on creating a publisher and a subscriber.

Note: Make sure you have a good understanding of publisher/subscriber nodes.

Setup

If you haven't already, you will need to create a ROS workspace to work in. You will also need to create a ROS package within that workspace.

Note: For this tutorial, we will assume your workspace is called tutorial-ws package is named tutorial-pkg.

Create a folder within the src directory of your package, called scripts. This is where we will store the scripts that define our nodes.

Note: We don't necessarily have to call the directory scripts. In fact, you don't even need to store the nodes in a separate directory. However, this is considered good practice.

Creating a Publisher

Within the scripts folder, create a file called publisher_example.py with the following contents

#!/usr/bin/env python
import rospy
from std_msgs.msg import String

def publisher_example():
    rospy.init_node('publisher_example')
    pub = rospy.Publisher('chatter', String, queue_size = 10)
    rate = rospy.Rate(10)

    while not rospy.is_shutdown():
        message = "Hello %s" % rospy.get_time()
        pub.publish(message)
        rospy.loginfo(rospy.get_caller_id() + " " + "I said %s" % message)
        rate.sleep()

if __name__ == '__main__':
    try:
        publisher_example()
    except rospy.ROSInterruptException:
        pass

The above script essentially creates a node called publisher_example which publishes a message to a topic called chatter at 10 Hz.

Note: If any part(s) of the above code is/are confusing, make sure you understand how publisher/subscriber nodes work.

Once you have created the script, you will need to make it an executable. To do so, within the scripts directory, run

chmod +x publisher_example.py

Creating a Subscriber

Within the scripts folder, create a file called subscriber_example.py with the following contents

#!/usr/bin/env python
import rospy
from std_msgs.msg import String

def callback_fnc(data):
  rospy.loginfo(rospy.get_caller_id() + " " + "I heard %s", data.data)

def subscriber_example():
    rospy.init_node('subscriber_example')
    sub = rospy.Subscriber('chatter', String, callback_fnc)
    
    rospy.spin() #listen for data.

if __name__ == '__main__':
    try:
        subscriber_example()
    except rospy.ROSInterruptException:
        pass

The above script essentially creates a node called subscriber_example which subscribes to messages from a topic called chatter and acknowledges these messages on the console.

Note: If any part(s) of the above code is/are confusing, make sure you understand how publisher/subscriber nodes work.

Once you have created the script, you will need to make it an executable. To do so, within the scripts directory, run

chmod +x subscriber_example.py

Building and Running the Nodes

Building the Nodes

If you have followed the above steps, you should now have a workspace called tutorial-ws with a package called tutorial-pkg which contains two executable files called publisher_example.py and subscriber_example.py within its src directory.

Note: For your convenience, we have provided the entire workspace for this example within the tutorial branch of our repository.

You must now rebuild and re-source the package.

cd ~/tutorial-ws/
catkin_make
source ./devel/setup.bash

And that's it!

Running the Nodes

To run the nodes, we suggest you open up 3 separate terminals, and do the following:

  1. In the first terminal, run roscore using

     roscore
    
  2. In the second terminal, run the publisher we created using

     rosrun tutorial publisher_example.py
    

    You should see logs similar to

     [INFO] [1580610805.295515]: /publisher_example I said Hello 1580610805.3
    
  3. In the third terminal, run the subscriber we created using

     rosrun tutorial subscriber_example.py
    

    You should see logs similar to

     [INFO] [1580610805.695598]: /subscriber_example I heard Hello 1580610805.3
    

Creating and Running a Launch File

Having to launch all these nodes separately every time is tedious, so let us create a launch file to make things easier.

Creating the Launch File

First, in a new terminal, navigate back to the package directory and create a folder called launch

cd ~/tutorial-ws/src/tutorial_package/
mkdir launch
cd launch

Create a file called launch_publisher_subscriber_example.launch within the launch directory, and add the following contents

<launch>
    <node pkg="tutorial-pkg" name="talker" type="publisher_example.py"/>
    <node pkg="tutorial-pkg" name="listener" type="subscriber_example.py"/>
</launch>

Now, go back to the package directory and make and source the package

cd ~/tutorial-ws/
catkin_make
source ./devel/setup.bash

Running the Launch File

You can now run the nodes using

roslaunch tutorial-pkg publisher_subscriber_example.launch

Note: roslaunch will automatically start roscore if it hasn't already been started.

Let's use rqt_graph and rqt_console to view information about the system.

In a new terminal, run

rqt_graph

You should see the rqt graph window with the following system graph:

Now, in another terminal, run

rqt_console

The rqt console window should open. Within it, you should see a logging section with logs similar to these

Next Steps

Now that you are comfortable with publisher/subscriber nodes, you can also try understanding service nodes.

Clone this wiki locally