Writing a Publisher (Python)

Create a package

First of all, you will have to create a new package, where you will place the code for your Publisher node. For this, you need to be in your ROS2 workspace src folder.

cd ~/ros2_ws/src

Now, execute the following command to create the package:

ros2 pkg create --build-type ament_python publisher_py --dependencies rclpy std_msgs

You will get an output similar to this one:

This will automatically generate your package and all its necessary files and folders. Now, navigate to the publisher_py/publisher_py folder in order to create your file.

Write the code

Inside the publisher_py/publisher_py folder, create a new file named publisher.py. Into this file, you will copy the following code

import rclpy
from rclpy.node import Node
from std_msgs.msg import Int32

class SimplePublisher(Node):

    def __init__(self):
        super().__init__('simple_publisher')
        self.publisher_ = self.create_publisher(Int32, 'counter', 10)
        timer_period = 0.5
        self.timer = self.create_timer(timer_period, self.timer_callback)
        self.i = 0

    def timer_callback(self):
        msg = Int32()
        msg.data = self.i
        self.publisher_.publish(msg)
        self.get_logger().info('Publishing: "%s"' % msg.data)
        self.i += 1

def main(args=None):
    rclpy.init(args=args)
    simple_publisher = SimplePublisher()
    rclpy.spin(simple_publisher)
    simple_publisher.destroy_node()
    rclpy.shutdown()

if __name__ == '__main__':
    main()

Review the code

First, we define our class, which inherits from the Node class.

class SimplePublisher(Node):

Next, we have the constructor of our class:

def __init__(self):

Within the constructor, we are initializing our node by calling to the constructor of the superclass Node.

super().__init__('simple_publisher')

Also within the constructor, we create our publisher_ and timer objects. Note that the timer object is bound to a function named timer_callback, which we will see next. This timer object will be triggered every 500ms.

self.publisher_ = self.create_publisher(Int32, 'counter', 10)
timer_period = 0.5
self.timer = self.create_timer(timer_period, self.timer_callback)

Finally, we also initialie a variable named i to 0.

self.i = 0

Next we have the definition of the timer_callback function we introduced before. Inside this function, we are creating an Int32 message, which is given the value of the self.i variable. Then, we are going to increase the value of this variable in 1, and we are going to publish the message into our topic. Remember that this function will be called every 500ms, as defined in the timer_ object.

def timer_callback(self):
    msg = Int32()
    msg.data = self.i
    self.publisher_.publish(msg)
    self.get_logger().info('Publishing: "%s"' % msg.data)
    self.i += 1

Finally, on the main function, all we do is create a SimplePublisher object, and make it spin until somebody terminates the program (Ctrl+C).

def main(args=None):
    rclpy.init(args=args)

    simple_publisher = SimplePublisher()

    rclpy.spin(simple_publisher)

    minimal_publisher.destroy_node()
    rclpy.shutdown()

Modify the setup.py file

In the entry_points section of your setup.py file, add the following lines:

entry_points={
    'console_scripts': [
        'publisher_node = publisher_py.publisher:main'
    ],
},

This will generate an executable, which points to the main function from the publisher.py file, which is inside the publisher_py folder.

Compile the package

First of all, let's go the ros2_ws folder in order to be able to compile.

cd ~/ros2_ws;

Let's now execute the colcon command in order to build our node.

colcon build --symlink-install

You will get an output like the following one:

Finally, let's source the workspace.

source ~/ros2_ws/install/setup.bash

Testing the publisher

Let's run our publisher with the following command:

ros2 run publisher_py publisher

Now, in order to visualize the output, let's execute in a different shell the following command:

ros2 topic echo /counter

In the Shell where you executed the publisher you will get an output like this:

And in the shell where you executed the echo command you will get the following:

Practice Online

Also, you can test this tutorial in ROSDS, using a ROSject which already contains all the code described in it. You can get the ROSject by clicking on the button below:

Above: Get ROSDS ROSject

The link above will take yo a page like the below one:

Now, you just need to Sign In (or Sign Up if you don't have an account yet) to ROSDS in order to launch the ROSject.