Skip to content

Creating ROS Package

Daniel Bara edited this page Nov 10, 2023 · 3 revisions

Guide to Creating a New ROS Package and a Simple Publisher Node

Note: This tutorial includes custom scripts which may or may not be stable, but it makes life easier. To know the regular way, reference the official guide.

1. Create a New ROS Package

To create the package called gra_capture, use:

> ccp gra_capture std_msgs rospy

Here's a brief explanation:

  • ccp is a wrapper for the command catkin_create_package, and makes sure you are running it in the correct directory (normally, you must CD into ~/catkin_ws/src). Has the same synax.
  • gra_capture is the name of the package.
  • std_msgs and rospy are dependencies of the package. Since the node will be written in Python and we might be using standard messages, these are essential.

2. Writing the Simple Publisher Node

You have now created a package. You will see it within the repository in ~/gra/ros/gra_capture. You can also quickly CD into it in the terminal using roscd gra_capture.

  1. Create a new file Python file for the publisher node called hello_publisher.py in gra_capture/src

  2. Edit the newly created file:

    #!/usr/bin/env python3
    
    import rospy
    from std_msgs.msg import String
    
    def talker():
        pub = rospy.Publisher('hello_topic', String, queue_size=10)
        rospy.init_node('hello_publisher', anonymous=True)
        rate = rospy.Rate(10) # 10hz
        while not rospy.is_shutdown():
            hello_str = "Hello, ROS world!"
            rospy.loginfo(hello_str)
            pub.publish(hello_str)
            rate.sleep()
    
    if __name__ == '__main__':
        try:
            talker()
        except rospy.ROSInterruptException:
            pass
  3. Make the script executable:

    > chmod +x hello_publisher.py

3. Building the Package

Use the alias to build the package:

> cb

This alias runs catkin build in the workspace directory and refreshes the environment. Essentially, this builds all the packages in the workspace, making your new node executable.

4. Running and Testing the Publisher Node

  1. Make sure you are running locally

    > setdevmaster # Custom command used in our repository
  2. Start the ROS core:

    > roscore
  3. In a new terminal, run the publisher node:

    > rosrun gra_capture hello_publisher.py
  4. In another terminal, listen to the published topic:

    > rostopic echo /hello_topic

You should see the output data: "Hello, ROS world!" being written continuously.

Clone this wiki locally