How to create a ROS2 Workspace

How to create a ROS2 Workspace

Hello ROS developers! In this post, you’ll learn how to create a ROS2 workspace in four easy steps 🙂 . Let’s go!

COMMANDS TO USE

* mkdir -p my_ros2_ws/src

* colcon build

* source ~/my_ros2_ws/install/local_setup.bash

The Four Easy Steps to Creating a ROS2 Workspace

Let’s jump straight in. Here I’m giving the four steps “upfront”; practical demonstrations follow.

Step Description
1 Install ROS2
I will use ROSDS for this example, which allows me to create a ROSject which already has ROS2 Crystal installed on it . Heck, no time to go through the installation now. Unless you have > 24 hours per day, you can try ROSDS too 🙂 
2 Create workspace directory
~$ mkdir -p ros2_ws/src && cd ros2_ws
3 Build workspace with colcon
~/ros2_ws$ colcon build
4 Source workspace setup files
~/ros2_ws$ source install/local_setup.bash && source install/setup.bash

Already got the idea? Great, rush off to your terminal and get the job done! The rest of us will proceed to the practicals.

Practicals: Executing the Four Easy Steps to Creating a ROS2 Workspace

Easier said than done, right? No, for this case, it’s easier done than said. Take a look:

Step 1

Either of the following will do:

  1. Use the ROS Development Studio (ROSDS), an online platform for developing for ROS within a PC browser. Easy-peasy. I’m using this option of this post. To open a “terminal” on ROSDS, pick the Shell app from the Tools menu.
  2. You have ROS2 installed on a local PC. Okay, skip to step 2.

Next step!

Step 2

Straight to the point:

root@086ad5448257:/# cd ~
root@086ad5448257:~# mkdir -p ros2_ws/src && cd ros2_ws
root@086ad5448257:~/ros2_ws#

Step 3

Now for the real deal…build the workspace:

root@086ad5448257:~/ros2_ws# colcon build

Summary: 0 packages finished [0.13s]
root@086ad5448257:~/ros2_ws# ll
total 24
drwxr-xr-x 6 root root 4096 Feb 20 20:19 ./
drwx------ 6 root root 4096 Feb 20 20:17 ../                      
drwxr-xr-x 2 root root 4096 Feb 20 20:19 build/
drwxr-xr-x 2 root root 4096 Feb 20 20:19 install/
drwxr-xr-x 3 root root 4096 Feb 20 20:19 log/
drwxr-xr-x 2 root root 4096 Feb 20 20:17 src/
root@086ad5448257:~/ros2_ws#

Step 4

Source the workspace, and you’re done:

root@086ad5448257:~/ros2_ws# source install/local_setup.bash && so
urce install/setup.bash
root@086ad5448257:~/ros2_ws#

Feedback

Did you like this post? Please leave a comment in the comments section below, so we can interact and learn from each other.

If you want to learn about other ROS topics, please let us know on the comments area and we will look into doing a post and/or video about it.

Thank you for reading and/or watching!

How to Publish & Subscribe to a ROS2 Topic Using Command line

How to Publish & Subscribe to a ROS2 Topic Using Command line

In this video you will learn how to publish and subscribe to a topic in ROS2 using the command line.

COMMANDS TO USE:

  • ros2 topic list
  • ros2 msg list
  • ros2 msg show std_msgs/String
  • ros2 topic pub /chatter std_msgs/String "data: Hello ROS Developers"
  • ros2 topic echo /chatter

RELATED ROS2 RESOURCES:

  • ROS2 Course for Beginners: Introduce you to the basic concepts that you need to know in order to start working with ROS2.
  • ROS Development Studio: Develop your first ROS2 project online (Ready online including Gazebo simulations + ros1_bridge)

The following steps take through the development as shown in the video:

  • Open ROS Development Studio and create a new project (use a suitable name for the project).
  • Activate the docker image for ROS2 by executing the following command in a SHELL
    $ docker run -it osrf/ros2:ardent-basic

 

  • The first command to know is ros2 topic list. This command is same as the rostopic list command in ros1.
  • The command for publishing a topic is ros2 topic pub. This command takes the topic name and message just like the rostopic pub command in ros1.
  • In ros2, we can use the command ros2 msg list to see all the supported message types

  • Now let’s see the usage with a String type message. We can see the structure of the String message with the following command
    $ ros2 msg show std_msgs/String

The output of this command will give us the information about the content of the message type String. To publish the message we will use the following command

$ ros2 topic pub /chatter std_msgs/String "data: Hello ROS Developers"

  • Once we execute the above command, a message will start publishing to the /chatter topic.

  • Next, we can check the published message by using ros2 topic echo command. This should show us the message on /chatter topic

    $ ros2 topic echo /chatter

The output of the above command should be the message that we encoded in the last command.

 

FEEDBACK:

Did you like this video? Whatever the case, please leave a comment on the comments section below, so we can interact and learn from each other.

If you want to learn about other ROS topics, please let us know on the comments area and we will do a video about it.


ros2-basics-course

[ROS2 tutorial]- How to launch a ROS2 node

[ROS2 tutorial]- How to launch a ROS2 node

Welcome to the ROS2 tutorial series. In this first video we are going to show How to launch a node in ROS2.

COMMANDS TO USE:

  • ros2 run
  • ros2 pkg list
  • ros2 pkg executables
  • source /opt/ros/crystal/setup.bash

Step1. Let’s do this in ROS Development Studio(RDS)

At first, we have to find a Linux computer, install ROS, build all the package we need and…crash…NOOOOO!!!

Of course, you can do all this painfully on your own computer, but…

We’ll use ROSDS through this ROS2 tutorial because we can easily build a project on it without setting up any environment locally. You can create an account here for free.

After logging in, click on the New ROSject button. Let’s call this project ros2_tutorial and open it by clicking on the Open ROSject button.

Step2. Launching a ROS2 node

If you know ROS1 you may remember that in order to run a node on that ROS version we use therosrun <package_name> <executable_name> command. With ROS2 it’s you almost don’t see any difference, given that we use  ros2 run<package_name> <executable_name>.

Before launching a node we first need to know the list of ROS2 packages installed. We can do that with the following command:

ros2 pkg list

With the command above we can see that among the packages we have one named demo_nodes_cpp, as can be seen with ros2 pkg list | grep demo. To see the list of ROS2 executable files on our system we can run the command below:

ros2 pkg executables

The output provided by the command below is a list of <package_name> <executable_name>.In case you want to reduce the output and list only the desired package, by using grep  we can do that. Given that we are interested on thedemo_nodes_cpppackage, let’s filter it with  ros2 pkg executables | grep demo_nodes_cpp.

The output will be something like:

demo_nodes_cpp add_two_ints_client
demo_nodes_cpp add_two_ints_client_async
demo_nodes_cpp add_two_ints_server
demo_nodes_cpp allocator_tutorial
demo_nodes_cpp imu_listener
demo_nodes_cpp list_parameters
demo_nodes_cpp list_parameters_async
demo_nodes_cpp listener
demo_nodes_cpp listener_best_effort
demo_nodes_cpp one_off_timer
demo_nodes_cpp parameter_events
demo_nodes_cpp parameter_events_async
demo_nodes_cpp parameter_node
demo_nodes_cpp reuse_timer
demo_nodes_cpp ros2param
demo_nodes_cpp set_and_get_parameters
demo_nodes_cpp set_and_get_parameters_async
demo_nodes_cpp talker
demo_nodes_cpp_native talker

We can see that we have among the executable files we have one called talker  and another one called listener. For former writes data on a topic while the latter listens to that topic and print the received messages.

Let’s first launch the listener in background:

ros2 run demo_nodes_cpp listener &

Now let’s launch the talker and see the logs of both nodes:

ros2 run demo_nodes_cpp talker

After running the talker you should see something like the messages below:

[INFO] [talker]: Publishing: "Hello world: 1"

[INFO] [listener]: I heard: [Hello world: 1] 

[INFO] [talker]: Publishing: "Hello world: 2"

[INFO] [listener]: I heard: [Hello world: 2] 

...

So this is the post for today. It is really simple, but let’s go step by step learning a little bit of ROS2 every day. Let’s keep pushing and we will be ROS2 experts in no time.

To conclude, in case you also want to learn ROS1, we have complete courses in python and C++ on that subject. You can take those courses by clicking on the links below:

Those are online courses in the Robot Ignite Academy, where you are going to learn ROS fast using online simulations.

RELATED RESOURCES:

 

FEEDBACK:

Did you like this post? Whatever the case, please leave a comment on the comments section of our youtube (https://www.youtube.com/watch?v=8NgpjHOVCV8) video associated to this post. You can also subscribe to our channel and press the bell for a new video every day.

Keep pushing your ROS learning.

How to create & test a Publisher in ROS2 (Python)

How to create & test a Publisher in ROS2 (Python)

Hello ROS developers! In this post lets’ see how to create and test a publisher in ROS2 using Python (rclpy).

I break it down into “5 easy steps”, let’s see one by one:

  1. Create a Python-based package in ROS2.
  2. Create the python code for your publisher.
  3. Edit package.xml.
  4. Replace CMakeLists.txt with setup.py.
  5. Run and test your python code in ROS2.

Let’s go!

1. Create a Python-based package in ROS2

At this point, I’m taking for granted that you already have the following in place:

  • Your ROS2 is installed and running. (Don’t have this? No issues, you can spin a free ROS2 development environment at ROSDS. No installation required, just a few clicks and you will have a fully-functional ROS2 installation within your browser.)
  • You have created a ROS2 workspace. Need help on this? See this tutorial.

Once you have crossed the two bridges above, you just need to run this command from the src folder of your ROS2 workspace:

~/ros2_ws/src$ ros2 pkg create ro2_pub_py

Here the name of the package is ros2_pub_py, and our workspace directory is ros2_ws. Feel free to name yours differently.

The final structure of your project should look something like this (when you have completed all steps):

Easy Step 1 done!

2. Create the python code for your publisher

Yes, you guessed right, we must write the publisher in Python, since this post says “using Python”. ROS2 official repo provides 3 different ways with examples on how to write the Python code.

In this post, we will use the “local function” method because…I like it and get to decide here :)…kidding…I think it’s still somewhat ROS1-like while showcasing the differences in ROS2. Take home bonus: try ‘translating’ the code into the “old school” and “member function” variants.

Enough small talk, let’s do the work! Create Python file located at `~/ros2_ws/src/ro2_pub_py/sos_publisher.py`. Here’s the code:

# Copyright 2016 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import rclpy

from std_msgs.msg import String


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

    node = rclpy.create_node('sos_publisher')
    publisher = node.create_publisher(String, 'sos')

    msg = String()
    
    def timer_callback():
        msg.data = 'ObiWan Kenobi, please help me. You\'re my only hope'
        node.get_logger().info('Publishing sos message: "%s"' % msg.data)
        publisher.publish(msg)

    timer_period = 0.5  # seconds
    timer = node.create_timer(timer_period, timer_callback)

    rclpy.spin(node)

    # Destroy the timer attached to the node explicitly
    # (optional - otherwise it will be done automatically
    # when the garbage collector destroys the node object)
    node.destroy_timer(timer)
    node.destroy_node()
    rclpy.shutdown()


if __name__ == '__main__':
    main()

A few notes about the code above:

  • The statement import rclpy imports the ROS2 Python module. This is equivalent to import rospy in ROS1.
  • The statement from std_msgs import String imports the type of message the publisher uses. Basically no change from ROS1.
  • The statements from rclpy.init(args=args) to publisher = node.create_publisher(String, 'sos')  initialize the ROS2 Python module and create a node sos_publisher publishing to the topic sos. Did you notice the subtle differences in how this is achieved in ROS1?
  • The variable timer provides similar functionality as rospy.Rate() in ROS1, providing the frequency at which a particular code block is repeated.

Next!

3. Edit package.xml

Actually, this step is technically part of creating the Python package, because the changes we are doing here is just indicating that it’s a Python package. But I wanted to call this out separately because I think it’s an important step.

Now, the original package.xml should look something like this after creating the package:

<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format2.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="2">
  <name>ros2_pub_py</name>
  <version>0.0.0</version>
  <description>TODO: Package description</description>
  <maintainer email="user@todo.todo">user</maintainer>
  <license>TODO: License declaration</license>

  <buildtool_depend>ament_cmake</buildtool_depend>

  <test_depend>ament_lint_auto</test_depend>
  <test_depend>ament_lint_common</test_depend>

  <export>
    <build_type>ament_cmake</build_type>
  </export>
</package>

Change to the following, following the example given in the official repo:

<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format2.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="2">
  <name>ros2_pub_py</name>
  <version>0.0.0</version>
  <description>TODO: Package description</description>
  <maintainer email="user@todo.todo">user</maintainer>
  <license>Apache License 2.0</license>

  <exec_depend>rclpy</exec_depend>
  <exec_depend>std_msgs</exec_depend>

  <!-- These test dependencies are optional
  Their purpose is to make sure that the code passes the linters -->
  <test_depend>ament_copyright</test_depend>
  <test_depend>ament_flake8</test_depend>
  <test_depend>ament_pep257</test_depend>
  <test_depend>python3-pytest</test_depend>

  <export>
    <build_type>ament_python</build_type>
  </export>
</package>

You can spot the differences, right? Great, next step!

4. Replace CMakeLists.txt with setup.py

Similar to step 3 above, this is also something that’s related to package creation that I decided to call out separately. These steps are necessary because as of now ROS2 package creator does not yet support Python-based packages out of the box (the package.xml and CMakeList.txt are created for a C-based package by default). Hopefully, a future release would make these steps unnecessary.

Not in some many words:

  • Delete CMakeList.txt; we don’t need it here.
  • Add a setup.py properly configured for the package and python program.

Here you go, following the official example:

from setuptools import setup

package_name = 'ros2_pub_py'

setup(
    name=package_name,
    version='0.0.0',
    packages=[],
    py_modules=[
        'sos_publisher',
    ],
    install_requires=['setuptools'],
    zip_safe=True,
    author='user',
    author_email="user@todo.todo",
    maintainer='user',
    maintainer_email="user@todo.todo",
    keywords=['ROS', 'ROS2'],
    classifiers=[
        'Intended Audience :: Developers',
        'License :: OSI Approved :: Apache Software License',
        'Programming Language :: Python',
        'Topic :: Software Development',
    ],
    description='TODO: Package description.',
    license='Apache License, Version 2.0',
    tests_require=['pytest'],
    entry_points={
        'console_scripts': [
            'sos_publisher = sos_publisher:main',
        ],
    },
)

Also, add a setup.cfg file to the same location as setup.py:

[develop]
script-dir=$base/lib/ros2_pub_py
[install]
install-scripts=$base/lib/ros2_pub_py

Done here. Last step!

5. Run and test your python code in ROS2

Now time to ros2 run your code, but not so fast! Before we become ros2-run-happy, we need to take care of some basic things so that we don’t have bad surprises.

In your ROS2 workspace directory, run:

~/ros2_ws$ colcon build

Yes, we need to rebuild the package, after all those changes.

Also, we need to run:

~/ros2_ws$ source install/setup.bash && source install/local_setup.bash

And then you’re ready for ros2-run:

ros2 run ros2_pub_py sos_publisher

You should see output similar to:

~/ros2_ws$ ros2 run ros2_pub_py sos_publisher
[INFO] [sos_publisher]: Publishing sos message: "ObiWan Kenobi, please help me. You're my only hope"
[INFO] [sos_publisher]: Publishing sos message: "ObiWan Kenobi, please help me. You're my only hope"
[INFO] [sos_publisher]: Publishing sos message: "ObiWan Kenobi, please help me. You're my only hope"
[INFO] [sos_publisher]: Publishing sos message: "ObiWan Kenobi, please help me. You're my only hope"
...

From another terminal, run the following commands and check the output:

~$ ros2 node list
/sos_publisher
~$ ros2 topic list
/parameter_events
/sos
~$ ros2 topic echo /sos
data: ObiWan Kenobi, please help me. You're my only hope

data: ObiWan Kenobi, please help me. You're my only hope

data: ObiWan Kenobi, please help me. You're my only hope

And we’re all done!

Final take away

I hope you found this post useful. I would suggest that you try following the post and creating your package from scratch, but in case you want to have a sneak-peek at the code used for this post, you can find it here: https://rds.theconstructsim.com/r/bayodesegun/ros2_demo_4698/.

Keep pushing your ROS2 learning!


ROS2 basics course

ROS2 basics course

[ROS Q&A] 173 – How to create Launch Files in ROS2

[ROS Q&A] 173 – How to create Launch Files in ROS2

In this video we’re going to show you how to create launch files in ROS2, compared with how we did for ROS1.

RELATED ROS RESOURCES&LINKS:
ROS Development Studio (ROSDS) —▸ http://rosds.online
Robot Ignite Academy –▸ https://www.robotigniteacademy.com

Enjoy ROS2! 🙂


Feedback

Did you like this video? Do you have questions about what is explained? Whatever the case, please leave a comment on the comments section below, so we can interact and learn from each other.

If you want to learn about other ROS topics, please let us know on the comments area and we will do a video about it 🙂

Pin It on Pinterest