Գլխավոր էջ ROS Robotics Projects: Build And Control Robots Powered By The Robot Operating System, Machine Learning,..

ROS Robotics Projects: Build And Control Robots Powered By The Robot Operating System, Machine Learning, And Virtual Reality

5.0 / 0
How much do you like this book?
What’s the quality of the file?
Download the book for quality assessment
What’s the quality of the downloaded files?
Build exciting robotics projects such as mobile manipulators, self-driving cars, and industrial robots powered by ROS, machine learning, and virtual reality Key Features:
• Create and program cool robotic projects using powerful ROS libraries
• Build industrial robots like mobile manipulators to handle complex tasks
• Learn how reinforcement learning and deep learning are used with ROS
Nowadays, heavy industrial robots placed in workcells are being replaced by new age robots called cobots, which don't need workcells. They are used in manufacturing, retail, banks, energy, and healthcare, among other domains. One of the major reasons for this rapid growth in the robotics market is the introduction of an open source robotics framework called the Robot Operating System (ROS).
This book covers projects in the latest ROS distribution, ROS Melodic Morenia with Ubuntu Bionic (18.04). Starting with the fundamentals, this updated edition of ROS Robotics Projects introduces you to ROS-2 and helps you understand how it is different from ROS-1. You'll be able to model and build an industrial mobile manipulator in ROS and simulate it in Gazebo 9. You'll then gain insights into handling complex robot applications using state machines and working with multiple robots at a time. This ROS book also introduces you to new and popular hardware such as Nvidia's Jetson Nano, Asus Tinker Board, and Beaglebone Black, and allows you to explore interfacing with ROS. You'll learn as you build interesting ROS projects such as self-driving cars, making use of deep learning, reinforcement learning, and other key AI concepts.
By the end of the book, you'll have gained the confidence to build interesting and intricate projects with ROS. What you will learn:
• Grasp the basics of ROS and understand ROS applications
• Uncover how ROS-2 is different from ROS-1
• Handle complex robot tasks using state machines
• Communicate with multiple robots and collaborate to build apps with them
• Explore ROS capabilities with the latest embedded boards such as Tinker Board S and Jetson Nano
• Discover how machine learning and deep learning techniques are used with ROS
• Build a self-driving car powered by ROS
• Teleoperate your robot using Leap Motion and a VR headset
Who this book is for: If you're a student, hobbyist, professional, or anyone with a passion for learning robotics and interested in learning about algorithms, motion control, and perception capabilities from scratch, this book is for you. This book is also ideal for anyone who wants to build a new product and for researchers to make the most of what's already available to create something new and innovative in the field of robotics.
2nd Ed.
Packt Publishing
456 / 449
ISBN 10:
ISBN 13:
PDF, 95.63 MB

Ձեզ կարող է հետաքրքրել Powered by Rec2Me


Հիմնական արտահայտություններ


To post a review, please sign in or sign up
Կարող եք ակնարկ թողնել գրքի վերաբերյալ և կիսվել ձեր փորձով: Մյուս ընթերցողներին նույնպես հետաքրքիր կլինի իմանալ ձեր կարծիքը իրենց կարդացած գրքերի վերաբերյալ: Անկախ նրանից՝ ձեզ դուր է գալիս գիրքը, թե ոչ, եթե անկեղծորեն և մանրակրկիտ պատմեք դրա մասին, մարդիկ կկարողանան իրենց համար նոր գրքեր գտնել, որոնք կհետաքրքրեն իրենց:
ROS Robotics Projects
Second Edition

Build and control robots powered by the Robot Operating
System, machine learning, and virtual reality

Ramkumar Gandhinathan
Lentin Joseph


ROS Robotics Projects
Second Edition
Copyright © 2019 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form
or by any means, without the prior written permission of the publisher, except in the case of brief quotations
embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented.
However, the information contained in this book is sold without warranty, either express or implied. Neither the
authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to
have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products
mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy
of this information.
Commissioning Editor: Vijin Boricha
Acquisition Editor: Meeta Rajani
Content Development Editor: Pratik Andrade
Senior Editor: Rahul Dsouza
Technical Editor: Dinesh Pawar
Copy Editor: Safis Editing
Project Coordinator: Anish Daniel
Proofreader: Safis Editing
Indexer: Rekha Nair
Production Designer: Alishon Mendonsa
First published: March 2017
Second edition: December 2019
Production reference: 1181219
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
B3 2PB, UK.
ISBN 978-1-83864-932-6


To my dear mother and father, for their sacrifices and for exemplifying the power of
To my influential sister, for her constant love and motivation.
To my loving wife, for being supportive, understanding my passion, and accepting me the way I
am throughout our life and beyond.
To all my friends and colleagues ; who've been by my side, encouraging and inspiring me to do
To Meeta, Pratik, and other Packt employees for working closely with me, bringing the best out
of me, and shaping the book.
– Ramkumar Gandhinathan
I dedicate this book to my parents, C. G. Joseph and Jancy Joseph, for giving me strong support
in making this project happen.
– Lentin Joseph


Subscribe to our online digital library for full access to over 7,000 books and videos, as well
as industry leading tools to help you plan your personal development and advance your
career. For more information, please visit our website.

Why subscribe?
Spend less time learning and more time coding with practical eBooks and Videos
from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Fully searchable for easy access to vital information
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and
ePub files available? You can upgrade to the eBook version at www.packt.com and as a print
book customer, you are entitled to a discount on the eBook copy. Get in touch with us at
customercare@packtpub.com for more details.
At www.packt.com, you can also read a collection of free technical articles, sign up for a
range of free newsletters, and receive exclusive discounts and offers on Packt books and

About the authors
Ramkumar Gandhinathan is a roboticist and researcher by profession. He started building
robots in the sixth grade and has been in the robotics field for over 15 years through
personal and professional connections. He has personally built over 80 robots of different
types. With 7 years' overall professional experience (4 years full-time and 3 years parttime/internship) in the robotics industry, he has 5 years of ROS experience. As a part of his
professional career, he has built over 15 industrial robot solutions using ROS. He is also
fascinated by building drones and is a drone pilot. His research interests and passion are in
the fields of SLAM, motion planning, sensor fusion, multi-robot communication, and
systems integration.
Lentin Joseph is an author, roboticist, and robotics entrepreneur from India. He runs a
robotics software company called Qbotics Labs in Kochi, Kerala. He has 8 years of
experience in the robotics domain, primarily in ROS, OpenCV, and PCL.
He has authored several books on ROS, namely Learning Robotics Using Python, first and
second edition; Mastering ROS for Robotics Programming, first and second edition; ROS
Robotics Projects, first edition; and Robot Operating System for Absolute Beginners.
He completed his master's degree in robotics and automation in India and has worked at
Robotics Institute, CMU, USA. He is also a TEDx speaker.

Packt is searching for authors like you
If you're interested in becoming an author for Packt, please visit authors.packtpub.com
and apply today. We have worked with thousands of developers and tech professionals,
just like you, to help them share their insight with the global tech community. You can
make a general application, apply for a specific hot topic that we are recruiting an author
for, or submit your own idea.

Table of Contents


Chapter 1: Getting Started with ROS
Technical requirements
Getting started with ROS

ROS distributions
Supported OSes
Robots and sensors supported by ROS
Why use ROS?

Fundamentals of ROS

The filesystem level
The computation graph level
The ROS community level
Communication in ROS

ROS client libraries
ROS tools

ROS Visualizer (RViz)

ROS simulators
Installing ROS Melodic on Ubuntu 18.04 LTS
Getting started with the installation
Configuring Ubuntu repositories
Setting up source.list
Setting up keys
Installing ROS Melodic
Initializing rosdep
Setting up the ROS environment
Getting rosinstall

Setting up ROS on VirtualBox
Introduction to Docker
Why Docker?
Installing Docker

Installing from the Ubuntu repository
Removing Docker
Installing from the Docker repository
Working with Docker

Setting up the ROS workspace
Opportunities for ROS in industries and research


Table of Contents

Chapter 2: Introduction to ROS-2 and Its Capabilities
Technical requirements
Getting started with ROS-2
ROS-2 distributions
Supported operating systems
Robots and sensors supported in ROS-2
Why ROS-2?

Fundamentals of ROS-2

What is DDS?
How is DDS implemented?
Computational graph
ROS-2 community level
Communication in ROS-2
Changes between ROS-1 and ROS-2

ROS-2 client libraries (RCL)
ROS-2 tools

Installing ROS-2

Getting started with the installation

Setting up the system locale
Adding ROS-2 repositories
Installing development and ROS tools

Getting the ROS-2 source code

Installing dependencies using rosdep
Installing DDS implementations (optional)
Building code

Setting up ROS-1, ROS-2, or both environments
Running test nodes

Setting up the ROS-2 workspace
Writing ROS-2 nodes

ROS-1 example code
ROS-2 example code
Differences between ROS-1 and ROS-2 talker nodes

Bridging ROS-1 and ROS-2

Testing the ros1_bridge package

Chapter 3: Building an Industrial Mobile Manipulator
Technical requirements
Understanding available mobile manipulators
Applications of mobile manipulators
Getting started building mobile manipulators
Units and coordinate system
Gazebo and ROS assumptions

[ ii ]


Table of Contents

Building the robot base

Robot base prerequisites

Robot base specifications
Robot base kinematics

Software parameters

ROS message format
ROS controllers

Modeling the robot base

Initializing the workspace
Defining the links
Defining the joints

Simulating the robot base

Defining collisions
Defining actuators

Testing the robot base

Getting started building the robot arm
Robot arm prerequisites

Robot arm specifications
Robot arm kinematics

Software parameters

The ROS message format
ROS controllers

Modeling the robot arm

Initializing the workspace
Defining the links
Defining the joints

Simulating the robot arm

Defining collisions
Defining actuators

Testing the robot arm

Putting things together

Modeling the mobile manipulator
Simulating and testing the mobile manipulator

Chapter 4: Handling Complex Robot Tasks Using State Machines
Technical requirements
Introduction to ROS actions
The client-server concept
An actionlib example – robot arm client
An actionlib example – battery simulator server-client

Creating a package and a folder action inside it
Creating an action file that has the goal, result, and feedback
Modifying the package files and compiling the package
Defining a server
Defining a client

[ iii ]


Table of Contents

Waiter robot analogy
Introduction to state machines
Introduction to SMACH
SMACH concepts
User data

Getting started with SMACH examples
Installing and using SMACH-ROS
Simple example
Restaurant robot analogy

Chapter 5: Building an Industrial Application
Technical requirements
Application use case – robot home delivery
Setting up the environment in Gazebo

Making our robot base intelligent
Adding a laser sensor
Configuring the navigation stack
Mapping the environment
Localizing the robot base

Making our robot arm intelligent

Introduction to Moveit
Installing and configuring Moveit for our mobile robot
Installing Moveit
Configuring the Moveit setup assistant wizard
Loading the robot model
Setting up self-collisions
Setting up planning groups
Setting up arm poses
Setting up passive joints
Setting up ROS controllers
Finalizing the Moveitconfig package

Controlling the robot arm using Moveit

Simulating the application

Mapping and saving the environment
Choosing the points on the environment
Adding the points to our library
Completing the state machine

Improvements to the robot
Chapter 6: Multi-Robot Collaboration
Technical requirements

[ iv ]


Table of Contents

Understanding the swarm robotics application
Swarm robot classification
Multiple robot communication in ROS
Single roscore and common networks
Issues with a common network

Using groups/namespaces
Example – multi-robot spawn using groups/namespaces
Issues with using groups/namespaces

Introduction to the multimaster concept

Introduction to the multimaster_fkie package
Installing the multimaster_fkie package
Setting up the multimaster_fkie package
Setting up hostnames and IPs
Checking and enabling the multicast feature
Testing the setup

A multi-robot use case
Chapter 7: ROS on Embedded Platforms and Their Control
Technical requirements
Understanding embedded boards

Important concepts
How different are microcontrollers and microprocessors in robotics?
What matters while choosing such boards

Introduction to microcontroller boards
Arduino Mega

How to choose an Arduino board for your robot

ROS-supported embedded boards

Comparison table

Introduction to single-board computers
CPU boards

Tinkerboard S
BeagleBone Black
Raspberry Pi

Comparison table
GPU boards
Jetson TX2
Jetson Nano

Comparison table

Debian versus Ubuntu
Setting up ROS on Tinkerboard S



Table of Contents

Installing the Tinkerboard Debian OS
Installing Armbian and ROS
Installing using an available ROS image

Setting up ROS on BeagleBone Black
Installing the Debian OS
Installing Ubuntu and ROS

Setting up ROS on Raspberry Pi 3/4
Installing Raspbian and ROS
Installing Ubuntu and ROS

Setting up ROS on Jetson Nano
Controlling GPIOS from ROS
Tinkerboard S
BeagleBone Black
Raspberry Pi 3/4
Jetson Nano

Benchmarking embedded boards
Getting started with Alexa and connecting with ROS
Alexa skill-building requirements
Creating a skill

Chapter 8: Reinforcement Learning and Robotics
Technical requirements
Introduction to machine learning
Supervised learning
Unsupervised learning
Reinforcement learning

Understanding reinforcement learning
Explore versus exploit
Reinforcement learning formula
Reinforcement learning platforms
Reinforcement learning in robotics

MDP and the Bellman equation
Reinforcement learning algorithms
Taxi problem analogy
TD prediction

Algorithm explanation

TD control

Off-policy learning – the Q-learning algorithm
Algorithm explanation

On-policy learning – the SARSA algorithm
Algorithm explanation

Installing OpenAI Gym, NumPy, and pandas
Q-learning and SARSA in action

[ vi ]


Table of Contents

Reinforcement learning in ROS

TurtleBot and its environment
Installing gym-gazebo and its dependencies
Testing the TurtleBot-2 environment


MARA and its environment
Installing gym-gazebo2 and dependencies
Testing the MARA environment

Chapter 9: Deep Learning Using ROS and TensorFlow
Technical requirements
Introduction to deep learning and its applications
Deep learning for robotics
Deep learning libraries
Getting started with TensorFlow
Installing TensorFlow on Ubuntu 18.04 LTS
TensorFlow concepts

Writing our first code in TensorFlow

Image recognition using ROS and TensorFlow
The ROS image recognition node

Running the ROS image recognition node

Introducing to scikit-learn

Installing scikit-learn on Ubuntu 18.04 LTS

Introduction to SVM and its application in robotics
Implementing an SVM-ROS application

Chapter 10: Creating a Self-Driving Car Using ROS
Technical requirements
Getting started with self-driving cars
The history of autonomous vehicles
Levels of autonomy

Components of a typical self-driving car
GPS, IMU, and wheel encoders
Xsens MTi IMU

Ultrasonic sensors

Velodyne HDL-64 LIDAR

[ vii ]


Table of Contents

SICK LMS 5xx/1xx and Hokuyo LIDAR
Continental ARS 300 radar (ARS)
The Delphi radar
Onboard computer

Software block diagram of self-driving cars

Simulating and interfacing self-driving car sensors in ROS
Simulating the Velodyne LIDAR
Interfacing Velodyne sensors with ROS
Simulating a laser scanner
Explaining the simulation code
Interfacing laser scanners with ROS
Simulating stereo and mono cameras in Gazebo
Interfacing cameras with ROS
Simulating GPS in Gazebo
Interfacing GPS with ROS
Simulating IMU on Gazebo
Interfacing IMUs with ROS
Simulating an ultrasonic sensor in Gazebo
Low-cost LIDAR sensors

Simulating a self-driving car with sensors in Gazebo
Installing prerequisites

Visualizing robotic car sensor data
Moving a self-driving car in Gazebo
Running hector SLAM using a robotic car

Interfacing a DBW car with ROS

Installing packages
Visualizing the self-driving car and sensor data
Communicating with DBW from ROS

Introducing the Udacity open source self-driving car project
Open source self-driving car simulator from Udacity

Chapter 11: Teleoperating Robots Using a VR Headset and Leap
Technical requirements
Getting started with a VR headset and Leap Motion
Designing and working on the project
Installing the Leap Motion SDK on Ubuntu 14.04.5
Visualizing the Leap Motion controller data
Playing with the Leap Motion Visualizer tool
Installing the ROS driver for the Leap Motion controller
Testing the Leap Motion ROS driver

Visualizing Leap Motion data in RViz
[ viii ]



Table of Contents

Creating a teleoperation node using the Leap Motion controller
Building a ROS-VR Android application
Working with the ROS-VR application and interfacing with Gazebo
TurtleBot simulation in VR
Installing the Turtlebot simulator
Working with TurtleBot in VR

Troubleshooting the ROS-VR application
Integrating the ROS-VR application and Leap Motion teleoperation
Chapter 12: Face Detection and Tracking Using ROS, OpenCV, and
Dynamixel Servos
Technical requirements
Overview of the project
Hardware and software prerequisites
Installing the usb_cam ROS package

Creating an ROS workspace for dependencies
Configuring a webcam on Ubuntu 18.04
Interfacing the webcam with ROS

Configuring a Dynamixel servo using RoboPlus
Setting up the USB-to-Dynamixel driver on the PC

Interfacing Dynamixel with ROS

Installing the ROS dynamixel_motor packages

Creating face tracker ROS packages

The interface between ROS and OpenCV

Working with the face-tracking ROS package
Understanding the face tracker code
Understanding CMakeLists.txt
The track.yaml file
Launch files
Running the face tracker node
The face_tracker_control package
The start_dynamixel launch file
The pan controller launch file

The pan controller configuration file
The servo parameters configuration file
The face tracker controller node
Creating CMakeLists.txt
Testing the face tracker control package
Bringing all of the nodes together
Fixing the bracket and setting up the circuit
The final run

Other Books You May Enjoy


[ ix ]

Table of Contents




Robot Operating System (ROS) is one of the most popular robotics middleware and is
used by universities and industries for robot-specific applications. Ever since its
introduction, many robots have been introduced to the market and users have been able to
use them with ease within their applications. One of its main draws is its open source
nature. ROS does not need a user to reinvent the wheel; instead, standardizing robot
operations and applications is simple.
This book is an upgrade to the previous edition and introduces you to newer ROS
packages, interesting projects, and some added features. This book targets projects in the
latest (at the time of writing) ROS distribution—ROS Melodic Morenia with Ubuntu Bionic
version 18.04.
Here, you will understand how robots are used in industries and will learn the step-by-step
procedure of building heterogeneous robot solutions. Unlike the service call and action
features in ROS, you will be introduced to cooler techniques that let robots handle intricate
tasks in a smart way. This knowledge should pave the way to far more intelligent and selfperforming autonomous robots. Additionally, we will also introduce ROS-2, so you can
learn the differences between this version and the previous ROS version and find help in
choosing a specific middleware for your application.
Industries and research institutes are focusing primarily on the fields of computer vision
and natural language processing. While the previous edition of this book introduced you to
some simple vision applications such as object detection and face tracking, this edition will
introduce you to one of the most widely used smart speaker platforms on the market,
Amazon's Alexa, and how to control robots using it. In parallel, we will introduce new
hardware, such as Nvidia Jetson, Asus Tinker Board, and BeagleBone Black and explore
their capabilities with ROS.
While people may know how to control robots individually, one of the most common
problems faced by users in the ROS community is the use of multiple robots working in
synchronization, whether they are of the same type or not. This becomes complicated, as
robots may follow similar topic names and may possibly lead to confusion in a sequence of
operations. This book helps in highlighting the possible conflicts and suggests solutions.


This book also touches on reinforcement learning, including how it can be used with
robotics and ROS. Furthermore, you will find the most interesting projects for building a
self-driving car, deep learning with ROS, and building teleoperation solutions using VR
headsets and Leap Motion, as they're currently trending and are being researched

Who this book is for
This book is for students, hobbyists, professionals, and individuals with a passion for
learning robotics technology. Additionally, it is aimed at those individuals who are most
interested in learning about and writing algorithms, motion control, and perception
capabilities from scratch. This might even help a start-up build a new product or help
researchers utilize what's already available and create something new and innovative. This
book is also intended for those people who would like to work in the software domain or
who want to have a career as a robotics software engineer.

What this book covers
Chapter 1, Getting Started with ROS, is a basic introductory chapter on ROS for beginners.

This chapter will help you get an idea of the ROS software framework and its concepts.

Chapter 2, Introduction to ROS-2 and Its Capabilities, introduces you to ROS-2, the newest

upgraded framework that helps us use ROS in real-time applications. This chapter is
organized in a similar manner to Chapter 1, Getting Started with ROS, such that users are
able to differentiate between both ROS versions and understand their capabilities and
Chapter 3, Building an Industrial Mobile Manipulator, is where you will learn how to build a

mobile robot and a robot arm and combine them both to be used in a virtual environment
and control them through ROS.

Chapter 4, Handling Complex Robot Tasks Using State Machines, introduces you to techniques

in ROS that could be adapted while using robots for continuous and complicated task

Chapter 5, Building an Industrial Application, is where you will combine the skills acquired
in Chapters 3, Building an Industrial Mobile Manipulator and Chapter 4, Handling Complex

Robot Tasks Using State Machines, effectively, to create a user application. Here, we will
demonstrate how to use the mobile manipulator to deliver products to houses in a


Chapter 6, Multi-Robot Collaboration, teaches you how to communicate between multiple

robots of the same or different category and control them separately and together in

Chapter 7, ROS on Embedded Platforms and Their Control, helps you understand the latest

embedded controller and processor boards, such as STM32-based controllers, Tinker Board,
Jetson Nano, and many more. We will also look at how to control their GPIOs via ROS and
control them via voice-based commands through Alexa.
Chapter 8, Reinforcement Learning and Robotics, introduces you to one of the most

commonly used learning techniques in robotics called reinforcement learning. In this
chapter, you will understand what reinforcement learning is and the math behind it using
examples. Additionally, we will discover how to incorporate this learning technique with
ROS by means of simple projects.
Chapter 9, Deep Learning Using ROS and TensorFlow, is a project made using a

trending technology in robotics. Using the TensorFlow library and ROS, we can implement
interesting deep learning applications. You can implement image recognition using deep
learning, and an application using SVM can be found in this chapter.
Chapter 10, Creating a Self-Driving Car Using ROS, is one of the more interesting projects in

this book. In this chapter, we will build a simulation of a self-driving car using ROS
and Gazebo.

Chapter 11, Teleoperating Robots Using a VR Headset and Leap Motion, shows you how to

control a robot's actions using a VR headset and Leap Motion sensor. You can play around
with VR, which is a trending technology these days.
Chapter 12, Face Detection and Tracking Using ROS, OpenCV, and Dynamixel Servos, takes

you through a cool project that you can make with ROS and the OpenCV library. This
project basically creates a face tracker application in which your face will be tracked in such
a way that the camera will always point to your face. We will use intelligent servos such as
Dynamixel to rotate the robot on its axis.

To get the most out of this book
You should have a powerful PC running a Linux distribution, preferably Ubuntu
18.04 LTS.
You can use a laptop or desktop with a graphics card, and RAM of at least 4 to 8
GB is preferred. This is actually for running high-end simulations in Gazebo, as
well as for processing point clouds and computer vision.



You should have the sensors, actuators, and I/O boards mentioned in the book
and should be able to connect them all to your PC. You also need Git installed to
clone the package files.
If you are a Windows user, it will be good to download VirtualBox and set up
Ubuntu on it. However, do note that you may have issues while you try to
interface real hardware to ROS when working with VirtualBox.

Download the example code files
You can download the example code files for this book from your account at
www.packt.com. If you purchased this book elsewhere, you can visit
www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:

Log in or register at www.packt.com.
Select the Support tab.
Click on Code Downloads.
Enter the name of the book in the Search box and follow the onscreen

Once the file is downloaded, please make sure that you unzip or extract the folder using the
latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https:/​/​github.​com/
PacktPublishing/​ROS-​Robotics-​Projects-​SecondEdition. In case there's an update to the
code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available
at https:/​/​github.​com/​PacktPublishing/​. Check them out!

Download the color images
We also provide a PDF file that has color images of the screenshots/diagrams used in this
book. You can download it here: http:/​/​www.​packtpub.​com/​sites/​default/​files/



Code in Action
Visit the following link to check out videos of the code being run:

Conventions used
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder names, filenames,

file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an
example: "Remove the CMakelists.txt file."
A block of code is set as follows:
def talker_main():
pub = rospy.Publisher('/chatter', String)
msg = String()
i = 0

Any command-line input or output is written as follows:
$ sudo apt-get update
$ sudo rosdep init

Bold: Indicates a new term, an important word, or words that you see on screen. For
example, words in menus or dialog boxes appear in the text like this. Here is an example:
"Click on Software & Updates and enable all of the Ubuntu repositories."
Warnings or important notes appear like this.

Tips and tricks appear like this.



Get in touch
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book
title in the subject of your message and email us at customercare@packtpub.com.
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes
do happen. If you have found a mistake in this book, we would be grateful if you would
report this to us. Please visit www.packtpub.com/support/errata, selecting your book,
clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the internet, we
would be grateful if you would provide us with the location address or website name.
Please contact us at copyright@packt.com with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in,
and you are interested in either writing or contributing to a book, please visit

Please leave a review. Once you have read and used this book, why not leave a review on
the site that you purchased it from? Potential readers can then see and use your unbiased
opinion to make purchase decisions, we at Packt can understand what you think about our
products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packt.com.


Getting Started with ROS
Robotics is one of the upcoming technologies that can change the world. Robots can replace
people in many ways, and we are all afraid of them stealing our jobs. One thing is for sure:
robotics will be one of the influential technologies of the future. When a new technology
gains momentum, the opportunities in that field also increase. This means that robotics and
automation can generate a lot of job opportunities in the future.
One of the main areas in robotics that can provide mass job opportunities is robotics
software development. As we all know, software gives life to a robot or any machine. We
can expand a robot's capabilities through software. If a robot exists, its capabilities, such as
control, sensing, and intelligence, are realized using software.
Robotics software involves a combination of related technologies, such as computer vision,
artificial intelligence, and control theory. In short, developing software for a robot is not a
simple task; it can require expertise in many fields.
If you're looking for mobile application development in iOS or Android, there is a Software
Development Kit (SDK) available to build applications in it, but what about robots? Is
there any generic software framework available? Yes. One of the more popular robotics
software frameworks is called the Robot Operating System (ROS).
In this chapter, we will take a look at an abstract concept of ROS and how to install it, along
with an overview of simulators and its use on virtual systems. We will then cover the basic
concepts of ROS, along with the different robots, sensors, and actuators that support
ROS. We will also look at ROS with respect to industries and research. This entire book is
dedicated to ROS projects, so this chapter will be a kick-start guide for those projects and
help you set up ROS.
The following topics are going to be covered in this chapter:
Getting started with ROS
Fundamentals of ROS
ROS client libraries

Getting Started with ROS

Chapter 1

ROS tools
ROS simulators
Installing ROS
Setting up ROS on VirtualBox
Introduction to Docker
Setting up the ROS workspace
Opportunities for ROS in industries and research
So, let's get started with ROS.

Technical requirements
Let's look into the technical requirements for this chapter:
ROS Melodic Morenia on Ubuntu 18.04 (Bionic)
VMware and Docker
Timelines and test platform:
Estimated learning time: On average, 65 minutes
Project build time (inclusive of compile and run time): On
average, 60 minutes
Project test platform: HP Pavilion laptop (Intel® Core™ i7-4510U
CPU @ 2.00 GHz × 4 with 8 GB Memory and 64-bit OS,

Getting started with ROS
ROS is an open source, flexible software framework for programming robots. ROS provides
a hardware abstraction layer in which developers can build robotics applications without
worrying about the underlying hardware. ROS also provides different software tools to
visualize and debug robot data. The core of the ROS framework is a message-passing
middleware in which processes can communicate and exchange data with each other, even
when they're running from different machines. ROS message passing can be synchronous
or asynchronous.


Getting Started with ROS

Chapter 1

Software in ROS is organized as packages, and it offers good modularity and reusability.
Using the ROS message-passing middleware and hardware abstraction layer, developers
can create tons of robotic capabilities, such as mapping and navigation (in mobile robots).
Almost all the capabilities in ROS will be robot agnostic so that all kinds of robots can use
it. New robots can directly use this capability package without modifying any code inside
the package.
ROS has widespread collaborations in universities, and lots of developers contribute to it.
We can say that ROS is a community-driven project supported by developers worldwide.
This active developer ecosystem distinguishes ROS from other robotic frameworks.
In short, ROS is the combination of Plumbing (or communication), Tools, Capabilities, and
Ecosystem. These capabilities are demonstrated in the following diagram:

The ROS equation (source: ros.org. licensed under Creative Commons CC-BY-3.0: https://creativecommons.org/licenses/by/3.0/us/legalcode)

The ROS project was started in 2007 at Stanford University under the name Switchyard.
Later on, in 2008, the development was undertaken by a robotic research startup called
Willow Garage. The major development in ROS happened in Willow Garage. In 2013, the
Willow Garage researchers formed the Open Source Robotics Foundation (OSRF). ROS is
actively maintained by OSRF now. Now, let's look at a few ROS distributions.
Here are links to their websites: Willow Garage:
OSRF: http:/​/​www.​osrfoundation.​org/​.

ROS distributions
The ROS distributions are very similar to Linux distributions, that is, a versioned set of ROS
packages. Each distribution maintains a stable set of core packages, up to the End Of Life
(EOL) of the distribution.
The ROS distributions are fully compatible with Ubuntu, and most of the ROS distributions
are planned according to their respective Ubuntu versions.


Getting Started with ROS

Chapter 1

The following are some of the latest ROS distributions (at the time of writing) that
are recommended for use from the ROS website (http:/​/​wiki.​ros.​org/​Distributions):

Latest ROS distributions (source: ros.org. licensed under Creative Commons CC-BY-3.0: https://creativecommons.org/licenses/by/3.0/us/legalcode)

The latest ROS distribution is Melodic Morenia. We will get support for this distribution up
until May 2023. One of the problems with this latest ROS distribution is that most of the
packages will not be available on it because it will take time to migrate them from the
previous distribution. If you are looking for a stable distribution, you can go for ROS
Kinetic Kame because the distribution started in 2016, and most of the packages are
available on this distribution. The ROS Lunar Loggerhead distribution will stop being
supported in May 2019, so I do not recommend that you use it.

Supported OSes
The main OS ROS is tuned for is Ubuntu. ROS distributions are planned according to
Ubuntu releases. Other than Ubuntu, it is partially supported by Ubuntu ARM, Debian,
Gentoo, macOS, Arch Linux, Android, Windows, and OpenEmbedded.
This table shows new ROS distributions and the specific versions of the supporting OSes:
ROS distribution

Supporting OSes
Ubuntu 18.04 (LTS) and 17.10, Debian 8, macOS (Homebrew),
Melodic Morenia (LTS)
Gentoo, and Ubuntu ARM
Ubuntu 16.04 (LTS) and 15.10, Debian 8, macOS (Homebrew),
Kinetic Kame (LTS)
Gentoo, and Ubuntu ARM

[ 10 ]

Getting Started with ROS

Jade Turtle
Indigo Igloo (LTS)

Chapter 1

Ubuntu 15.04, 14.10, and 14.04, Ubuntu ARM, macOS
(Homebrew), Gentoo, Arch Linux, Android NDK, and Debian 8
Ubuntu 14.04 (LTS) and 13.10, Ubuntu ARM, macOS (Homebrew),
Gentoo, Arch Linux, Android NDK, and Debian 7

ROS Melodic and Kinetic are Long-Term Support (LTS) distributions that come with the
LTS version of Ubuntu. The advantage of using LTS distribution is that we will get
maximum lifespan and support.
We will look at a few robots and sensors that are supported by ROS in the next section.

Robots and sensors supported by ROS
The ROS framework is one of the most successful robotics frameworks, and universities
around the globe contribute to it. Because of its active ecosystem and open source nature,
ROS is being used in a majority of robots and is compatible with major robotic hardware
and software. Here are some of the most famous robots completely running on ROS:

Popular robots supported by ROS (Source: ros.org. Licensed under Creative Commons CC-BY-3.0: https://creativecommons.org/licenses/by/3.0/us/legalcode)

[ 11 ]

Getting Started with ROS

Chapter 1

The names of the robots listed in preceding images are Pepper (a), REEM-C (b), Turtlebot
(c), Robonaut (d), and Universal Robots (e).
The robots supported by ROS are listed at the following link: http:/​/​wiki.​ros.​org/
The following are the links where you can get the ROS packages of these robots:
Pepper: http:/​/​wiki.​ros.​org/​Robots/​Pepper
REEM-C: http:/​/​wiki.​ros.​org/​Robots/​REEM-​C
Turtlebot 2: http:/​/​wiki.​ros.​org/​Robots/​TurtleBot
Robonaut: http:/​/​wiki.​ros.​org/​Robots/​Robonaut2
Universal robotic arms: http:/​/​wiki.​ros.​org/​universal_​robot
Some popular sensors that support ROS are as follows:

Popular robot sensors supported in ROS

The names of the sensors in the preceding image are Velodyne (a), ZED Camera (b),
Teraranger (c), Xsens (d), Hokuyo Laser range finder (e), and Intel RealSense (f).

[ 12 ]

Getting Started with ROS

Chapter 1

The list of sensors supported by ROS is available at the following link: http:/​/​wiki.​ros.
The following are the links to the ROS wiki pages of these sensors:
Velodyne (a): http:/​/​wiki.​ros.​org/​velodyne
ZED Camera (b): http:/​/​wiki.​ros.​org/​zed-​ros-​wrapper
Teraranger (c): http:/​/​wiki.​ros.​org/​teraranger
Xsens (d): http:/​/​wiki.​ros.​org/​xsens_​driver
Hokuyo Laser range finder (e): http:/​/​wiki.​ros.​org/​hokuyo_​node
Intel real sense (f): http:/​/​wiki.​ros.​org/​realsense_​camera
Now, let's look at the advantages of using ROS.

Why use ROS?
The main intention behind building the ROS framework is to become a generic software
framework for robots. Even though there was robotics research happening before ROS,
most of the software was exclusive to their own robots. Their software may be open source,
but it is very difficult to reuse.
Compared to existing robotic frameworks, ROS is outperforming in the following aspects:
Collaborative development: As we've already discussed, ROS is open source
and free to use for industries and research. Developers can expand the
functionalities of ROS by adding packages. Almost all ROS packages work on a
hardware abstraction layer, so it can be reused easily for other robots. So, if one
university is good in mobile navigation and another is good in robotic
manipulators, they can contribute that to the ROS community and other
developers can reuse their packages and build new applications.
Language support: The ROS communication framework can be easily
implemented in any modern programming language. It already supports
popular languages such as C++, Python, and Lisp, and it has experimental
libraries for Java and Lua.
Library integration: ROS has an interface to many third-party robotics libraries,
such as Open Source Computer Vision (OpenCV), Point Cloud Library (PCL),
Open-NI, Open-Rave, and Orocos. Developers can work with any of these
libraries without much hassle.

[ 13 ]

Getting Started with ROS

Chapter 1

Simulator integration: ROS also has ties to open source simulators such as
Gazebo and has a good interface with proprietary simulators such as Webots and
Code testing: ROS offers an inbuilt testing framework called rostest to check
code quality and bugs.
Scalability: The ROS framework is designed to be scalable. We can perform
heavy computation tasks with robots using ROS, which can either be placed on
the cloud or on heterogeneous clusters.
Customizability: As we have already discussed, ROS is completely open source
and free, so we can customize this framework as per the robot's requirements. If
we only want to work with the ROS messaging platform, we can remove all of
the other components and use only that. We can even customize ROS for a
specific robot for better performance.
Community: ROS is a community-driven project, and it is mainly led by OSRF.
The large community support is a great plus for ROS and means we can easily
start robotics application development.
The following are the URLs of libraries and simulators that can be integrated with ROS:
Open-CV: http:/​/​wiki.​ros.​org/​vision_​opencv
PCL: http:/​/​wiki.​ros.​org/​pcl_​ros
Open-NI: http:/​/​wiki.​ros.​org/​openni_​launch
Open-Rave: http:/​/​openrave.​org/​
Orocos: http:/​/​www.​orocos.​org/​
V-REP: http:/​/​www.​coppeliarobotics.​com/​
Let's go through some of the basic concepts of ROS; these can help you get started with
ROS projects.

Fundamentals of ROS
Understanding the basic working of ROS and its terminology can help you understand
existing ROS applications and build your own. This section will teach you important
concepts that we are going to use in the upcoming chapters. If you find that a topic is
missing in this chapter, then rest assured that it will be covered in a corresponding
chapter later.
There are three different concepts in ROS. Let's take a look at them.

[ 14 ]

Getting Started with ROS

Chapter 1

The filesystem level
The filesystem level explains how ROS files are organized on the hard disk:

The ROS filesystem level

As you can see from the preceding diagram, the filesystem in ROS can be categorized
mainly as metapackages, packages, package manifest, messages, services, codes, and
miscellaneous files. The following is a short description of each component:
Metapackages: Metapackages group a list of packages for a specific application.
For example, in ROS, there is a metapackage called navigation for mobile robot
navigation. It can hold the information of related packages and helps install those
packages during its own installation.
Packages: The software in ROS is mainly organized as ROS packages. We can say
that ROS packages are the atomic build units of ROS. A package may consist of
ROS nodes/processes, datasets, and configuration files, all organized in a single
Package manifest: Inside every package will be a manifest file called
package.xml. This file consists of information such as the name, version, author,
license, and dependencies that are required of the package. The package.xml
file of a metapackage consists of the names of related packages.

[ 15 ]

Getting Started with ROS

Chapter 1

Messages (msg): ROS communicates by sending ROS messages. The type of
message data can be defined inside a file with the .msg extension. These files are
called message files. Here, we are going to follow a convention where we put the
message files under our_package/msg/message_files.msg.
Service (srv): One of the computation graph level concepts is services. Similar to
ROS messages, the convention is to put service definitions under
This sums up the ROS filesystem.

The computation graph level
The ROS computation graph is a peer-to-peer based network that processes all the
information together. The ROS graph concept constitutes nodes, topics, messages, master,
parameter server, services, and bags:

The ROS computational graph concept diagram

[ 16 ]

Getting Started with ROS

Chapter 1

The preceding diagram shows the various concepts in the ROS computational graph. Here
is a short description of each concept:
Nodes: ROS nodes are simply processes that use ROS APIs to communicate with
each other. A robot may have many nodes to perform its computations. For
example, an autonomous mobile robot may have a node each for hardware
interfacing, reading laser scan, and localization and mapping. We can create ROS
nodes using ROS client libraries such as roscpp and rospy, which we will be
discussing in the upcoming sections.
Master: The ROS master works as an intermediate node that aids connections
between different ROS nodes. The master has all of the details about all the nodes
running in the ROS environment. It will exchange details of one node with
another to establish a connection between them. After exchanging this
information, communication will start between the two ROS nodes.
Parameter server: The parameter server is a pretty useful thing in ROS. A node
can store a variable in the parameter server and set its privacy, too. If the
parameter has a global scope, it can be accessed by all other nodes. The ROS
parameter runs along with the ROS master.
Messages: ROS nodes can communicate with each other in many ways. In all the
methods, nodes send and receive data in the form of ROS messages. The ROS
message is a data structure that's used by ROS nodes to exchange data.
Topics: One of the methods to communicate and exchange ROS messages
between two ROS nodes is called ROS topics. Topics are named buses in which
data is exchanged using ROS messages. Each topic will have a specific name, and
one node will publish data to a topic and another node can read from the topic
by subscribing to it.
Services: Services are another kind of communication method, similar to topics.
Topics use publish or subscribe interaction, but in services, a request or reply
method is used. One node will act as the service provider, which has a service
routine running, and a client node requests a service from the server. The server
will execute the service routine and send the result to the client. The client node
should wait until the server responds with the results.
Bags: Bags are a useful utility in ROS for the recording and playback of ROS
topics. While working on robots, there may be some situations where we need to
work without actual hardware. Using rosbag, we can record sensor data and
copy the bag file to other computers to inspect data by playing it back.
This sums up the computational graph concept.

[ 17 ]

Getting Started with ROS

Chapter 1

The ROS community level
The ROS community has grown more now compared to the time it was introduced. You
can find at least 2,000+ packages being supported, altered, and used by the community
actively. The community level comprises the ROS resources for sharing software and

ROS community level diagram

Here is a brief description of each section:
Distributions: ROS distributions are versioned collections of ROS packages, such
as Linux distributions.
Repositories: ROS-related packages and files depend on a Version Control
System (VCS) such as Git, SVN, and Mercurial, using which developers around
the world can contribute to the packages.
ROS Wiki: The ROS community wiki is the knowledge center of ROS, in which
anyone can create documentation of their packages. You can find standard
documentation and tutorials about ROS on the ROS wiki.
Mailing lists: Subscribing to ROS mailing lists enables users to get new updates
regarding ROS packages and gives them a place to ask questions about ROS
ROS Answers: The ROS Answers website is the stack overflow of ROS. Users
can ask questions regarding ROS and related areas (http:/​/​answers.​ros.​org/
Blog: The ROS blog provides regular updates about the ROS community with
photos and videos (http:/​/​www.​ros.​org/​news).
Now, let's learn how communication is carried out in ROS in the next section.

[ 18 ]

Getting Started with ROS

Chapter 1

Communication in ROS
Let's learn how two nodes communicate with each other using ROS topics. The following
diagram shows how this happens:

Communication between ROS nodes using topics

As you can see, there are two nodes named talker and listener. The talker node publishes a
string message called Hello World into a topic called /talker, while the listener node is
subscribed to this topic. Let's see what happens at each stage, marked (1), (2), and (3) in the
preceding diagram:
1. Before running any nodes in ROS, we should start the ROS Master. After it has
been started, it will wait for nodes. When the talker node (publisher) starts
running, it will connect to the ROS Master and exchange the publishing topic
details with the master. This includes the topic name, message type, and
publishing node URI. The URI of the master is a global value, and all the nodes
can connect to it. The master maintains the tables of the publisher connected to it.
Whenever a publisher's details change, the table updates automatically.

[ 19 ]

Getting Started with ROS

Chapter 1

2. When we start the listener node (subscriber), it will connect to the master and
exchange the details of the node, such as the topic going to be subscribed to, its
message type, and the node URI. The master also maintains a table of
subscribers, similar to the publisher.
3. Whenever there is a subscriber and publisher for the same topic, the master node
will exchange the publisher URI with the subscriber. This will help both nodes to
connect and exchange data. After they've connected, there is no role for the
master. The data is not flowing through the master; instead, the nodes are
interconnected and exchange messages.
More information on nodes, their namespaces, and usage can be found here: http:/​/​wiki.
Now that we know the fundamentals of ROS, let's look at a few ROS client libraries.

ROS client libraries
ROS client libraries are used to write ROS nodes. All of the ROS concepts are implemented
in client libraries. So, we can just use it without implementing everything from scratch. We
can implement ROS nodes with a publisher and subscriber, write service callbacks, and so
on using client libraries.
The main ROS client libraries are in C++ and Python. Here is a list of popular ROS client
roscpp: This is one of the most recommended and widely used ROS client

libraries for building ROS nodes. This client library has most of the ROS concepts
implemented and can be used in high-performance applications.
rospy: This is a pure implementation of the ROS client library in Python. The
advantage of this library is its ease of prototyping, which means that
development time isn't as long. It is not recommended for high-performance
applications, but it is perfect for non-critical tasks.
roslisp: This is the client library for LISP and is commonly used to build robot
planning libraries.
Details of all the client ROS libraries can be found at the following link: http:/​/​wiki.​ros.
org/​Client%20Libraries. The next section will give us an overview of different ROS tools.

[ 20 ]

Getting Started with ROS

Chapter 1

ROS tools
ROS has a variety of GUI and command-line tools to inspect and debug messages. These
tools come in handy when you're working in a complex project involving a lot of package
integrations. It would help to identify whether the topics and messages are published in the
right format and are available to the user as desired. Let's look at some commonly used

ROS Visualizer (RViz)
RViz (http:/​/​wiki.​ros.​org/​rviz) is one of the 3D visualizers available in ROS that can
visualize 2D and 3D values from ROS topics and parameters. RViz helps to visualize data
such as robot models, robot 3D transform data (TF), point cloud, laser and image data, and
a variety of different sensor data:

Point cloud data visualized in RViz

The preceding screenshot shows a 3D point cloud scan from a Velodyne sensor placed on
an autonomous car.

[ 21 ]

Getting Started with ROS

Chapter 1

The rqt_plot program (http:/​/​wiki.​ros.​org/​rqt_​plot) is a tool for plotting scalar
values that are in the form of ROS topics. We can provide a topic name in the Topic box:


The preceding screenshot is a plot of a pose from the turtle_sim node.

[ 22 ]

Getting Started with ROS

Chapter 1

The rqt_graph (http:/​/​wiki.​ros.​org/​rqt_​graph) ROS GUI tool can visualize the graph
of interconnection between ROS nodes:


The complete list of ROS tools is available at the following link: http:/​/​wiki.​ros.​org/
Since we now have a brief idea of the ROS tools, we can cover different ROS simulators.

[ 23 ]

Getting Started with ROS

Chapter 1

ROS simulators
One of the open source robotic simulators tightly integrated with ROS is Gazebo (http:/​/
gazebosim.​org). Gazebo is a dynamic robotic simulator that has a wide variety of robot
models and extensive sensor support. The functionalities of Gazebo can be added via
plugins. The sensor values can be accessed by ROS through topics, parameters, and
services. Gazebo can be used when your simulation needs full compatibility with ROS.
Most of the robotics simulators are proprietary and expensive; if you can't afford it, you can
use Gazebo directly without any issues:

Gazebo simulator

The preceding is a PR2 robot model from OSRF. You can find the model at https:/​/
github.​com/​pr2/​pr2_​common, in the description folder.
The ROS interface of Gazebo is available at the following link: http:/​/

[ 24 ]

Getting Started with ROS

Chapter 1

Now that we know about the simulators of ROS, we can begin installing ROS Melodic on

Installing ROS Melodic on Ubuntu 18.04
As we have already discussed, there are a variety of ROS distributions available to
download and install, so choosing the exact distribution for our needs may be confusing.
The following are the answers to some of the questions that are asked frequently while
choosing a distribution:
Which distribution should I choose to get maximum support?
Answer: If you are interested in getting maximum support, choose an LTS
release. It will be good if you choose the second-most recent LTS
I need the latest features of ROS; which should I choose?
Answer: Go for the latest version; you may not get the latest complete
packages immediately after the release. You may have to wait a few months
after the release. This is because of the migration period from one
distribution to another.
In this book, we are dealing with two LTS distributions: ROS Kinetic, which is a stable
release, and ROS Melodic, the latest one. Our chapters will use ROS Melodic Morenia.

[ 25 ]

Getting Started with ROS

Chapter 1

Getting started with the installation
Go to the ROS installation website (http:/​/​wiki.​ros.​org/​ROS/​Installation). You will see
a screen listing the latest ROS distributions:

Latest ROS distributions on the website

You can get the complete installation instructions for each distribution if you click on ROS
Kinetic Kame or ROS Melodic Morenia.
We'll now step through the instructions to install the latest ROS distribution.

Configuring Ubuntu repositories
We are going to install ROS Melodic on Ubuntu 18.04 from the ROS package repository.
The repository will have prebuilt binaries of ROS in .deb format. To be able to use
packages from the ROS repository, we have to configure the repository options of Ubuntu

[ 26 ]

Getting Started with ROS

Chapter 1

The details of the different kinds of Ubuntu repositories can be found at https:/​/​help.
To configure the repository, perform the following steps:
1. First, search for Software & Updates in the Ubuntu search bar:

Ubuntu Software & Updates

[ 27 ]

Getting Started with ROS

Chapter 1

2. Click on Software & Updates and enable all of the Ubuntu repositories, as
shown in the following screenshot:

The Ubuntu Software & Updates center

Now that we've enabled the preceding set conditions, we can move on to the next step.

Setting up source.list
The next step is to allow ROS packages from the ROS repository server, called
packages.ros.org. The ROS repository server details have to be fed into source.list,
which is in /etc/apt/.
The following command will do this for ROS Melodic:
$ sudo sh -c 'echo "deb http://packages.ros.org/ros/ubuntu $(lsb_release sc) main" > /etc/apt/sources.list.d/ros-latest.list'

Let's set up the keys now.

[ 28 ]

Getting Started with ROS

Chapter 1

Setting up keys
When a new repository is added to Ubuntu, we should add the keys to make it trusted and
to be able to validate the origin of the packages. The following key should be added to
Ubuntu before starting installation:
$ sudo apt-key adv --keyserver hkp://ha.pool.sks-keyservers.net:80 --recvkey 421C365BD9FF1F717815A3895523BAEEB01FA116

Now, we are sure that we are downloading from an authorized server.

Installing ROS Melodic
Now, we are ready to install ROS packages on Ubuntu. Follow these steps to do so:
1. The first step is to update the list of packages on Ubuntu. You can use the
following command to update the list:
$ sudo apt-get update

This will fetch all the packages from the servers that are in source.list.
2. After getting the package list, we have to install the entire ROS package suite
using the following command:
$ sudo apt-get install ros-melodic-desktop-full

This will install most of the important packages in ROS. You will need at least 15
GB of space in your root Ubuntu partition to install and work with ROS.

Initializing rosdep
The rosdep tool in ROS helps us easily install the dependencies of the packages that we are
going to compile. This tool is also necessary for some core components of ROS.
This command launches rosdep:
$ sudo rosdep init
$ rosdep update

Here, while the first command was called, a file called 20-default.list was created in
/etc/ros/rosdep/sources.list.d/, with a list of links that connect to the respective

[ 29 ]

Getting Started with ROS

Chapter 1

Setting up the ROS environment
Congratulations! We are done with the ROS installation, but what next?
The ROS installation mainly consists of scripts and executables, which are mostly installed
to /opt/ros/<ros_version>.
To get access to these commands and scripts, we should add ROS environment variables to
the Ubuntu Terminal. It's easy to do this. To access ROS commands from inside the
Terminal, we have to source the /opt/ros/<ros_version>/setup.bash file.
Here's the command to do so:
$ source /opt/ros/melodic/setup.bash

But in order to get the ROS environment in multiple Terminals, we should add the
command to the .bashrc script, which is in the home folder. The .bashrc script will be
sourced whenever a new Terminal opens:
$ echo "source /opt/ros/melodic/setup.bash" >> ~/.bashrc
$ source ~/.bashrc

We can install multiple ROS distributions on Ubuntu. If there are multiple distributions, we
can switch to each ROS distribution by changing the distribution name in the preceding

Getting rosinstall
Last but not least, there is the ROS command-line tool, called rosinstall, for installing
source trees for particular ROS packages. The tool is based on Python, and you can install it
using the following command:
$ sudo apt-get install python-rosinstall

We are done with the ROS installation. Just check whether the installation is successful by
running the following commands:
Open a Terminal window and run the roscore command:
$ roscore

Run a turtlesim node in another Terminal:
$ rosrun turtlesim turtlesim_node

[ 30 ]

Getting Started with ROS

Chapter 1

If everything is correct, you will see the following output:

The turtlesim node GUI and Terminal with pose information

If you respawn the turtlesim node a couple of times, you should see the turtle changing.
We have now successfully installed ROS on Ubutu. Now, let's learn how to set up ROS on

Setting up ROS on VirtualBox
As you know, complete ROS support is only present on Ubuntu. So, what about Windows
and macOS users? Can't they use ROS? Yes, they can, using a tool called VirtualBox
(https:/​/​www.​virtualbox.​org/​). VirtualBox allows us to install a guest OS without
affecting the host OS. The virtual OS can work along with the host OS in a given
specification of a virtual computer, such as the number of processors and RAM and hard
disk size.
You can download VirtualBox for popular OSes from the following link: https:/​/​www.
The complete installation procedure for Ubuntu on VirtualBox is shown in the following
tutorial video on YouTube: https:/​/​www.​youtube.​com/​watch?​v=​QbmRXJJKsvs.

[ 31 ]

Getting Started with ROS

Chapter 1

The following is a screenshot of the VirtualBox GUI. You can see the virtual OS list on the
left-hand side and the virtual PC configuration on the right-hand side. The buttons for
creating a new virtual OS and starting the existing VirtualBox are on the top panel. The
optimal virtual PC configuration is shown in the following screenshot:

The VirtualBox configuration

[ 32 ]

Getting Started with ROS

Chapter 1

Here are the main specifications of the virtual PC:
Number of CPUs: 1
Display | Video Memory: 128 MB
Acceleration: 3D
Storage: 20 GB to 30 GB
Network adapter: NAT
In order to have hardware acceleration, you should install drivers from the VirtualBox
Guest addons disc. After booting into the Ubuntu desktop, navigate to Devices | Insert
Guest Addition CD Image. This will mount the CD image in Ubuntu and ask the user to
run the script to install drivers. If we allow it, it will automatically install all of the drivers.
After a reboot, you will get full acceleration on the Ubuntu guest.
There is no difference in ROS installation on VirtualBox. If the virtual network adapter is in
NAT mode, the internet connection of the host OS will be shared with the guest OS, so the
guest can work the same as the real OS. We now have ROS set up on VirtualBox.
The next section is an introduction to Docker.

Introduction to Docker
Docker is a piece of free software and the name of the company that introduced it to open
source community. You might have heard of virtual environments in Python, where you
can create isolated environments for your projects and install dedicated dependencies that
do not cause any trouble with other projects in other environments. Docker is similar,
where we can create isolated environments for our projects called containers. Containers
work like virtual machines but aren't actually similar to virtual machines. While virtual
machines need a separate OS on top of the hardware layer, containers do not and work
independently on top of the hardware layer, sharing the resources of the host machine.

[ 33 ]

Getting Started with ROS

Chapter 1

This helps us consume less memory and it is often speedier than virtual machines. The best
example to show the difference between both is shown here:

Differences between a virtual machine and Docker

Now that we know the difference between a virtual machine and Docker, let's understand
why we use Docker.

Why Docker?
In ROS, a project may consist of several metapackages that contain subpackages, and those
would need dependencies to work on. It could be quite annoying for a developer to set up
packages in ROS as it is quite common that different packages would use different or the
same dependencies of different versions and those could lead to compilation issues. The
best example would be when we want to use OpenCV3 with ROS Indigo while working
with vision algorithms or gazebo_ros_controller packages with different plugin
versions, causing the famous gravity error (https:/​/​github.​com/​ros-​simulation/​gazebo_
ros_​pkgs/​issues/​612). By the time the developer tries to rectify them, he/she might end up
losing other working projects due to replaced packages or dependency version changes.
While there might be different ways to handle this problem, a practical way to go about this
problem in ROS would be to use Docker containers. Containers are fast and can start or
stop, unlike any process in an OS in a matter of seconds. Any upgrades or updates on the
OS, or packages would not affect the containers inside or other containers in place.

[ 34 ]

Getting Started with ROS

Chapter 1

Installing Docker
Docker can be installed in two ways: using the Ubuntu repositories or using the official
Docker repository:
If you would just like to explore and save a couple of minutes with just a single
line installation, go ahead and install from the Ubuntu repository.
If you would like to explore more options with Docker other than what is
intended in this book, I would suggest that you go ahead and install from official
Docker repositories as they will have the most stable and bug-fixed packages
with added features.
Before going ahead with either of the following installations, ensure you
update the apt package index using $ sudo apt-get update.

Installing from the Ubuntu repository
To install Docker from the Ubuntu repository, use the following command:
$ sudo apt-get install docker.io

If you've changed your mind and would like to try out installing from the Docker
repository or if you wish to remove the Docker version you installed via the preceding step,
move on to the next step.

Removing Docker
If you're not interested in the old Docker version and want to install the latest stable
version, remove Docker using the following command and install it from the Docker
$ sudo apt-get remove docker docker-engine docker.io containerd runc

The preceding is a general command to remove Docker, docker-engine,
docker.io (as these are the older version names), and runtime
containers, if any were pulled or created.

[ 35 ]

Getting Started with ROS

Chapter 1

Installing from the Docker repository
To install Docker from the official repository, follow these steps:
1. First, we use the following command:
$ sudo apt-get install apt-transport-https ca-certificates curl
gnupg-agent software-properties-common

2. Then, we add the official GPG key from Docker:
$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo
apt-key add -

3. Set up the Docker repository using the following command:
$ sudo add-apt-repository "deb [arch=amd64]
https://download.docker.com/linux/ubuntu bionic stable"

There are three types of update channels called the stable, nightly, and test
channels. The test channel provides the prereleases that are ready for
testing before availability, the nightly channel is the work in progress or
beta version, and stable is the finalized bug-fixed channel. The best
suggestion from the Docker team is the stable channel; however, you're
free to test either channels by replacing the term stable with either
nightly or test.
4. Update the apt package index once again:
$ sudo apt-get update

5. Now, install the Docker package using the following command:
$ sudo apt install docker-ce

6. After installing via either method, you could check the versions of Docker for
both types of installation using the following command:
$ docker --version

The current version that is available in the Ubuntu repository is 17.12, while the latest
release version at the time of writing this book is 18.09 (stable version).
Docker can only be run as a root user by default. Hence, add your username to the Docker
group using the following command:
$ sudo usermod -aG docker ${USER}

[ 36 ]

Getting Started with ROS

Chapter 1

Ensure you reboot the system for the preceding to take effect; otherwise, you will face
a permission denied error, as shown here:

Permission denied error

A quick fix to the preceding error would be to use sudo before any Docker commands.

Working with Docker
Containers are built from Docker images and these images can be pulled from Docker Hub
(https:/​/​hub.​docker.​com/​). We can pull ROS containers from the ros repository using the
following command:
$ sudo docker pull ros:melodic-ros-core

If everything is successful, you see the output shown here:

Successful Docker pull

[ 37 ]

Getting Started with ROS

Chapter 1

You can choose the specific version of ROS you want to work with. The best suggestion for
any application is to start with melodic-core, where you would continue to work and
update the container related to your project goal and not have other unnecessary
components installed. You can view Docker images using this command:
$ sudo docker images

By default, all of the containers are saved in /var/lib/docker. Using the preceding
command, you can identify the repository name and tag. In my case, for the ros repository
name, my tag was melodic-ros-core; hence, you could run the ros container using the
following command:
$ sudo docker run -it ros:melodic-ros-core

Other information the $ docker images command gives is the container ID, which
is 7c5d1e1e5096 in my case. You will need it when you want to remove the container.
Once you're inside Docker, you can check the ROS packages that are available using the
following command:
$ rospack list

When you run and exit Docker, you would've created another container, so for beginners,
it's quite common to create a list of containers unknowingly. You could use $ docker ps
-a or $ docker ps -l to view all active/inactive containers or the latest container and
remove containers using $ docker rm <docker_name>. To continue working in the same
container, you could use the following command:
$ sudo docker start -a -i silly_volhard

Here, silly_volhard is the default name created by Docker.
Now that you've opened the same container, let's install an ROS package and commit
changes to the Docker. Let's install the actionlib_tutorials package using the
following command:
$ apt-get update
$ apt-get install ros-melodic-actionlib-tutorials

Now, when you check the ROS packages list once again, you should be able to view a few
extra packages. Since you have modified the container, you would need to commit it to
experience the modifications while reopening the Docker image. Exit the container and
commit using the following command:
$ sudo docker commit 7c5d1e1e5096 ros:melodic-ros-core

[ 38 ]

Getting Started with ROS

Chapter 1

Now that we have installed ROS on Ubuntu and VirtualBox, let's learn how to set up the
ROS workspace.

Setting up the ROS workspace
After setting up ROS on a real PC, VirtualBox, or Docker, the next step is to create a
workspace in ROS. The ROS workspace is a place where we keep ROS packages. In the
latest ROS distribution, we use a catkin-based workspace to build and install ROS
packages. The catkin system (http:/​/​wiki.​ros.​org/​catkin) is the official build system of
ROS, which helps us build the source code into a target executable or libraries inside the
ROS workspace.
Building an ROS workspace is an easy task; just open a Terminal and follow these
1. The first step is to create an empty workspace folder and another folder called
src to store the ROS package in. The following command will do this for us. The
workspace folder name here is catkin_ws:
$ mkdir -p catkin_ws/src

2. Switch to the src folder and execute the catkin_init_workspace command.
This command will initialize a catkin workspace in the current src folder. We
can now start creating packages inside the src folder:
$ cd ~/catkin_ws/src
$ catkin_init_workspace

3. After initializing the catkin workspace, we can build the packages inside the
workspace using the catkin_make command. We can also build the workspace
without any packages:
$ cd ~/catkin_ws/
$ catkin_make

[ 39 ]

Getting Started with ROS

Chapter 1

4. This will create additional folders called build and devel inside the ROS

The catkin workspace folders

5. Once you've built the workspace, to access packages inside the workspace, we
should add the workspace environment to our .bashrc file using the following
$ echo "source ~/catkin_ws/devel/setup.bash" >> ~/.bashrc
$ source ~/.bashrc

6. When everything is done, you can verify that everything is correct by executing
the following command:

This command will print the entire ROS package path. If your workspace path is
in the output, you are done:

The ROS package path

You will see that two locations are sourced as ROS_PACKAGE_PATH. The former is the recent
edition we made in step 5 and the latter is the actual ROS installed packages folder. With
this, we have set up the ROS workspace. We will now look at the different opportunities for
ROS in industries and research.

[ 40 ]

Getting Started with ROS

Chapter 1

Opportunities for ROS in industries and
Now that we've installed ROS and set up our ROS workspace, we can discuss the
advantages of using it. Why is learning ROS so important for robotics researchers? The
reason is that ROS is becoming a generic framework for programming all kinds of robots.
So, robots in universities and industries mainly use ROS.
Here are some famous robotics companies using ROS for their robots:
Fetch Robotics: http:/​/​fetchrobotics.​com/​
Clearpath Robotics: https:/​/​www.​clearpathrobotics.​com/​
PAL Robotics: http:/​/​www.​pal-​robotics.​com/​en/​home/​
Yujin Robot: http:/​/​yujinrobot.​com/​
DJI: http:/​/​www.​dji.​com/​
ROBOTIS: http:/​/​www.​robotis.​com/​html/​en.​php
Knowledge of ROS will help you land a robotics application engineering job easily. If you
go through the skillset of any job related to robotics, you're bound to find ROS on it.
There are independent courses and workshops in universities and industries to teach ROS
development in robots. Knowing ROS will help you to get an internship and MS, Ph.D.,
and postdoc opportunities from prestigious robotic institutions such as CMU's Robotics
Institute (http:/​/​www.​ri.​cmu.​edu/​) and UPenn's GRAP lab (https:/​/​www.​grasp.​upenn.
The following chapters will help you build a practical foundation and core skills in ROS.

This chapter was an introductory chapter to get you started with robotics application
development using ROS. The main aim of this chapter was to get you started with ROS by
installing and understanding it. This chapter can be used as a kick-start guide for ROS
application development and can help you understand the following chapters, which
mainly demonstrate ROS-based applications. At the end of this chapter, we saw job and
research opportunities related to ROS and saw that a lot of companies and universities are
looking for ROS developers for different robotics applications.
From the next chapter onward, we will discuss ROS-2 and its capabilities.

[ 41 ]

Introduction to ROS-2 and Its
ROS or, to be more specific, ROS-1, has helped robotics reach a different milestone in the
open source community. While there were difficulties connecting the hardware and
software and synchronizing them, ROS-1 paved the way for a simple communication
strategy that has helped the community to connect any sophisticated sensor to a
microcomputer or microcontroller with ease. Over the past decade, ROS-1 has grown and
has a huge package list, where each and every package solves a problem either in bits or in
full, and has eliminated the concept of reinventing the wheel. These packages have led to a
whole new way of looking at robotics and providing intelligence to the currently available
systems. Connecting several such smaller packages could create a new complex
autonomous system on its own.
Though ROS-1 has given us the liberty of communicating with complex hardware and
software components with ease, there are some intricacies involved while producing them
as a product. For instance, let's say that, in the manufacturing industry, there is a swarm of
heterogeneous robots (robots of different types—say, mobile robots, robot arms, and so on).
It is quite difficult to establish communication between them due to the way ROS-1 is
architectured. This is because ROS-1 doesn't support the multi master concept.

Introduction to ROS-2 and Its Capabilities

Chapter 2

Although there are other ways (which we will explore in Chapter 6, Multi-Robot
Collaboration) we can use to communicate between nodes across the network, there is no
secure way of communicating between them. Anyone connected to the master node would
easily be able to gain access to a list of available topics and use or modify them. People
often use ROS-1 for working on proof-of-concepts or as a quick workaround for research
A marginal line has been drawn between using ROS-1 for prototyping and creating final
products, and this gap isn't likely to be reduced. This is mainly because ROS-1 isn't realtime. Network connectivity varies between system components while using a wired
connection (Ethernet) over a wireless connection (Wi-Fi). This could lead to a delay in data
reception or even loss of data.
Keeping this in mind, OSRF began its journey toward improving and building the nextgeneration ROS, called ROS-2. It is being developed to fix the risks faced by ROS-1. In this
chapter, you will be introduced to ROS-2, its differences with ROS-1, and its features. This
chapter is organized in the same manner as the previous chapter for better understanding
and comparison:
Getting started with ROS-2
Fundamentals of ROS-2
ROS-2 client libraries
ROS-2 tools
Installing ROS-2
Setting up the ROS-2 workspace
Writing ROS-2 nodes
Bridging ROS-1 and ROS-2

[ 43 ]

Introduction to ROS-2 and Its Capabilities

Chapter 2

Technical requirements
Let's look into the technical requirements for this chapter:
ROS 2 (source installation) on Ubuntu 18.04 (Bionic)
Timelines and test platform:
Estimated learning time: On average, 90 minutes
Project build time (inclusive of compile and run time): On
average, 60 minutes
Project test platform: HP Pavilion laptop (Intel® Core™ i7-4510U
CPU @ 2.00 GHz × 4 with 8 GB Memory and 64-bit OS,
The code for this chapter is available at https:/​/​github.​com/​PacktPublishing/​ROSRobotics-​Projects-​SecondEdition/​tree/​master/​chapter_​2_​ws/​src/​ros2_​talker.
Now, let's get started with ROS-2.

Getting started with ROS-2
ROS-2 is a deterministic effort toward improving the communication network framework
that will be used with real-time systems and production-ready solutions. ROS-2 aims to do
the following:
Provide secure communication between components
Communicate in real time
Connect multiple robots with ease
Improve the quality of communication irrespective of the communication
Provide an ROS layer directly onto hardware, such as sensors and embedded
Use the latest software improvements

[ 44 ]

Introduction to ROS-2 and Its Capabilities

Chapter 2

Remember the ROS equation diagram from the previous chapter? ROS-2 follows the exact
same equation but in a different manner:

ROS equation with DDS implementation (source: ros.org. Licensed under Creative Commons CC-BY-3.0: https://creativecommons.org/licenses/by/3.0/us/legalcode)

ROS-2 follows an industrial standard and implements real-time communication through a
concept called DDS implementation. DDS (short for Data Distributed Services) is a proven
industry standard by Object Management Groups (OMGs) and it is implemented by
many vendors such as RTI's implementation, called Connext (https:/​/​www.​rti.​com/
products/​), ADLink's implementation, called OpenSplice RTPS (https:/​/​github.​com/
ADLINK-​IST/​opensplice), and eProsima's implementation, called Fast RTPS (http:/​/​www.
These standards are used in time-critical applications such as airline systems, hospitals,
financial services, and space exploration systems. This implementation aims to simplify the
plumbing strategy (the publish-subscribe infrastructure) and make it deterministic across
different hardware and software components. This ensures that the user can concentrate on
the capabilities and ecosystem more.

[ 45 ]

Introduction to ROS-2 and Its Capabilities

Chapter 2

ROS-2 distributions
After a couple of years of alpha and beta version releases, the first official stable version of
ROS-2 was released in December 2017. The distro was named Ardent Apalone, a typical
alphabetical order naming style OSRF usually follows to name their ROS distributions. The
second release was in June 2018, called Bouncy Bolson. This version came with added
features and bug fixes and support for Ubuntu 18.04 and Windows 10 with Visual Studio
2017. The third version was called Crystal Clemmys and was released in December 2018.
All of the ROS distributions are code-named. For instance, this release is code-named
crystal, while the former two are named bouncy and ardent, respectively.
At the time of writing this book, the latest version is Dashing Diademata, which
was released on May 31, 2019 and code-named dashing.
Ardent and bouncy have already reached their End Of License (EOL) deadlines and hence
aren't supported. The third stable release, crystal, has an EOL deadline of December 2019
and the only long-term stable release is dashing, which has an EOL deadline of May 2021.

Supported operating systems
ROS-2 supports Linux, Windows, macOS, and Real-Time Operating Systems (RTOS) OS
layers, while ROS-1 only supported Linux and macOS layers. Though there is support
available from the ROS community on Windows, it wasn't officially supported by OSRF.
The following table shows the ROS distributions and specific versions of supported
operating systems:
ROS distributions Supported operating systems
Ubuntu 18.04 (Bionic—arm64 and amd64), Ubuntu 18.04 (Bionicarm32), macOS 10.12 (Sierra), Windows 10 with Visual Studio 2019,
Dashing Diademata
Debian Stretch(9)—arm64, amd64 and arm32, and OpenEmbedded
Thud (2.6)
Ubuntu 18.04 (Bionic); Ubuntu 16.04 (Xenial)—source build available,
Crystal Clemmys
not Debian package; macOS 10.12 (Sierra); and Windows 10
Ubuntu 18.04 (Bionic); Ubuntu 16.04 (Xenial)—source build available,
Bouncy Bolson
not Debian package; macOS 10.12 (Sierra); and Windows 10 with
Visual Studio 2017
Ardent Apalone
Ubuntu 16.04 (Xenial), macOS 10.12 (Sierra),and Windows 10
The ROS distro that's targeted in this book is Dashing Diademata, the third ROS-2 release.

[ 46 ]

Introduction to ROS-2 and Its Capabilities

Chapter 2

Robots and sensors supported in ROS-2
ROS-2 is being widely used and supported by research institutes and industries, especially
the robot manufacturing industry. The following are links to the robots and sensors that are
supported in ROS-2:
Turtlebot 2 (a): https:/​/​github.​com/​ros2/​turtlebot2_​demo
Turtlebot 3 (b): https:/​/​github.​com/​ROBOTIS-​GIT/​turtlebot3/​tree/​ros2
Mara robot arm (c): https:/​/​github.​com/​AcutronicRobotics/​MARA
Dr. Robot's Jaguar 4x4 (d): https:/​/​github.​com/​TRI-​jaguar4x4/​jaguar4x4
Intel Realsense camera (e): https:/​/​github.​com/​intel/​ros2_​intel_​realsense
Ydlidar (f): https:/​/​github.​com/​Adlink-​ROS/​ydlidar_​ros2
For now, the ROS-2 page doesn't have a dedicated page of robots and sensors that are
supported on the ROS-2 platform. The preceding robots and sensor packages are efforts
from manufacturers and researchers to use ROS-2 with their hardware and provide it to the

Why ROS-2?
ROS-2 is designed to work similarly to ROS-1, keeping in mind the robotics community. It
is standalone and is not a part of ROS-1. It does, however, interpolate and work alongside
ROS-1 packages. ROS-2 is being developed to overcome the challenges faced by ROS-1 by
using modern dependencies and tools. Unlike ROS-1, whose feature stack was written in
C++, and the client libraries were written in C++ and Python (where Python was built using
a ground-up approach and was written based on C++ libraries), the components in ROS-2
are written in the C language. There is a separate layer written in C that connects to ROS-2
client libraries such as rclcpp, rclpy, and rcljava.
ROS-2 has better support for various network configurations and provides reliable
communication. ROS-2 also eliminates the concept of nodelets
(http://wiki.ros.org/nodelet) and supports multi-node initialization. Unlike ROS-1, a
couple of pretty interesting features in ROS-2 are the heartbeat detection of a node through
a state machine cycle and notifications when nodes and topics are added or removed. These
could help design fault-tolerant systems. Also, ROS-2 is soon expected to support different
platforms and architectures.

[ 47 ]

Introduction to ROS-2 and Its Capabilities

Chapter 2

Now that we've understood how ROS-2 sets itself apart from ROS-1, let's look at its
fundamentals for a detailed explanation.

Fundamentals of ROS-2
In ROS-1, the user code would connect to the ROS client libraries (such as rospy or
roscpp) and they would communicate directly with other nodes from within the network,
whereas in ROS-2, the ROS client libraries act like an abstraction layer and connect to
another layer that communicates with the network using other nodes through DDS
implementation. A simple comparison is shown here:

Comparison between ROS-1 and ROS-2

As you can see, in ROS-2, the communication with the OS layer and further down to the
hardware layer is done through DDS implementation. The DDS component in the
preceding diagram is vendor-specific and implemented by the vendors.
The abstract DDS layer component is connected via ROS-2 and helps the user connect their
code through DDS implementation. This way, the user need not be explicitly aware of the
DDS APIs as they come through ROS-2. Also, ROS-1 uses a custom transport protocol, as
well as a custom central discovery mechanism, hence the usage of the master node. ROS-2,
on the other hand, has the abstract DDS layer, through which serialization, transport, and
discovery are being provided.

[ 48 ]

Introduction to ROS-2 and Its Capabilities

Chapter 2

What is DDS?
As we mentioned earlier, DDS is a standard defined by OMG. It is a publish-subscribe
transport technique similar to the one used in ROS-1. The DDS implements a distributed
discovery system technique that helps two or more DDS programs communicate with each
other without the use of the ROS master, unlike ROS-1. The discovery system need not be
dynamic and vendors who implement DDS provide options for static discovery.

How is DDS implemented?
There are multiple DDS implementations supported in ROS-2 since different vendors offer
different features. For instance, RTI's Connext may be specifically implemented either for
microcontrollers or toward applications requiring safety certifications. In all cases, DDS is
implemented through a special layer called the ROS middleware interface layer (or rmw), as
shown here:

ROS-2 middleware layer

The user code is the topmost block and contains the user logic or the algorithm. In ROS-1,
the user code usually sits on top of the ROS client library (such as roscpp or rospy) and
these libraries help the user connect their code with other components in ROS (such as
nodes, topics, or services). Unlike the ROS-client library in ROS-1, the ROS-client library in
ROS-2 is split into two layers:

[ 49 ]

Introduction to ROS-2 and Its Capabilities

Chapter 2

One specific to the programming language (such as rclcpp, rclpy, or rcljava)
so that it can handle threading processes such as rosspin and intra-process
communication like memory management
One common layer called rcl, implemented in C, that handles the names,
services, parameters, time, and console logging
The ROS middleware layer, rmw, is also a C implementation and connects with the DDS
implementations on top of the hardware layer. This layer is responsible for the service calls,
node discovery, graph events, and publish/subscribe calls with Quality of Services (QoS).
QoS in ROS-2 is a measure of performance across nodes in the network. By default, ROS-2
follows eProsima's Fast RTPS implementation since it is open source.

Computational graph
ROS-2 follows the same computational graph concept as ROS-1 but with some changes:
Nodes: Nodes are called participants in ROS-2. Apart from how nodes are
defined in the ROS-1 computational graph, there is a possibility to initialize more
than one node in a process. They may be located in the same process, different
processes, or different machines.
Discovery: While there is a master concept in ROS-1 that aids in communicating
between nodes, there is no concept of a master in ROS-2. Don't panic! By default,
the DDS standard implementation provides a distributed discovery method
where nodes automatically discover themselves in the network. This aids in
communication between multiple robots of different types.
Apart from this, the rest of the concepts that we looked at in the previous chapter, such as
messages, topics, the parameter server, services, and bags, are the same for ROS-2.

ROS-2 community level
Unlike the ROS-1 community, the ROS-2 community has begun to have some insights.
There are good contributions from several research institutes and industries. Since ROS-2
only started its development in 2014, there is lots more information regarding ROS-2
research and tools to watch out for since implementing real-time systems—especially in an
open source community—is one huge mountain to climb.

[ 50 ]

Introduction to ROS-2 and Its Capabilities

Chapter 2

OSRF has been communicating really well with vendors that offer DDS implementation
and contribute to the community. While ROS-1 has around 2,000+ packages in its
repository, ROS-2 has around 100+ packages. The latest ROS-2 page is https:/​/​index.​ros.

Communication in ROS-2
If you have completed the previous chapter successfully, you must be familiar with how
ROS-1 uses a simple publish-subscribe model where a master node is used to establish a
connection between nodes and communicate data. As we mentioned previously, ROS-2
works in a slightly different way. Since DDS implementation is used in ROS-2, the DDS
Interoperability Real-Time Publish-Subscribe Protocol (DDSI-RTPS) is used. The idea is
to establish secure and efficient communication between nodes, even in heterogeneous

The DCPS model

As you can see, there are additional components that are involved in this communication
method. As we mentioned previously, a node is called a participant in ROS-2. Each
participant can have single or multiple DDS topics and these topics are neither publishers
nor subscribers, like in ROS-1, but are referred to as code objects in ROS-2.

[ 51 ]

Introduction to ROS-2 and Its Capabilities

Chapter 2

These DDS topics are available in the global data space. From these topics, DDS publishers
and subscribers are created but they do not directly publish to or subscribe to a topic. These
are the responsibilities of components called data writers and data readers. Data writers
and data readers write or read data in a specialized message type, and this is how
communication is achieved in ROS-2. These levels of abstraction are necessary to ensure the
secure and efficient transfer of data. A user can set QoS settings at each level to provide the
highest granularity of configuration.

Changes between ROS-1 and ROS-2
This section specifies the differences between ROS-1 and ROS-2 so that you can understand
what upgrades are targeted in ROS-2. For ease of understanding, they're represented in the
following table:



Continuous Integration for
Continuous Integration for
Ubuntu 16.04 and 18.04,
Ubuntu 16.04
OS X EL Capitan, and
Community support: macOS.
Windows 10.

OS layers

Linux and macOS.

Linux, macOS, Windows, and


C++ 03
Python 2.

C++ 11, 14, and 17
Python 3.5.

Build system


Environment setup

Build multiple packages

Node initiation

ament and colcon.
Here, the build tool generates
Here, the build tool generates
package-specific and
scripts that would need to be
workspace-specific scripts so
sourced into the environment to use
that only those specific
the packages built in the
packages are sourced into the
environment for usage.
Multiple packages are built in a
Isolated builds are supported
single CMake context, hence the
where each package is built
possibility of colliding target
Only one node per process.

[ 52 ]

Multiple nodes allowed
per process.

Introduction to ROS-2 and Its Capabilities

Chapter 2

Apart from the preceding changes, there are other changes, all of which can be found
at http:/​/​design.​ros2.​org/​articles/​changes.​html.
Now that we have covered the fundamentals of ROS-2, let's look at the ROS-2 client

ROS-2 client libraries (RCL)
As we saw in the previous chapter, ROS client libraries are nothing but APIs for
implementing ROS concepts. Hence, we can directly use them in our user code to access
ROS concepts such as nodes, services, and topics. ROS client libraries come with the ease of
connecting with multiple programming languages.
Since each programming language has its own advantages and disadvantages, it's left to
the users to decide which to choose from. For instance, if a system is concerned with
efficiency and faster response rates, you could choose rclcpp, and if the system demands
prototyping as a priority with respect to the development time that's utilized, you could
choose rclpy.
The ROS client libraries in ROS-2 are split into two sections: one is language-specific (such
as rclcpp, rclpy, and rcljava) and the other contains common functionalities that are
implemented in the C language. This keeps the client library thin, lightweight, and easy to
While a developer writes code in ROS, there is a high chance that the code could go for
various iterations and changes with respect to the way it might be needed to connect with
other nodes or participants in the network. There may be a need to change the logic in
which ROS concepts are implemented in the code. Hence, the developer may need to worry
only about the intra-process communication and threading processes in their code as they
are language-specific implementations; ros::spin(), for instance, may have different
methods of implementation in C++ and Python.

[ 53 ]

Introduction to ROS-2 and Its Capabilities

Chapter 2

The changes that are made in the language-specific layer would not directly affect the ROS
concepts layer and hence maintaining several client libraries is easy when it comes to bug


The preceding diagram shows the RCL structure, where all the language-specific ROS
components sit on the layers below the user code (rclcpp, rclpy, rcljava, and rclcs).
The next common layer, rcl, is a C implementation and consists of ROS-specific functions
such as names, namespaces, services, topics, time, parameters, and logging information.
This allows any language-specific layer to connect with the rcl layer and establish
communication between different nodes or participants with ease.
This section gave us an overview of the fundamentals of ROS-2. Now, let's look at ROS-2

ROS-2 tools
Unlike ROS-1, ROS-2 provides tools for debugging message logs and topic information as
well. ROS-2 supports visual and command-line tools. However, since there is heavy
development in ROS-2, not all the tools have been ported yet. You can still use ROS-1 tools
using a ROS-1 to ROS-2 bridge (shown in the upcoming sections) for development.

[ 54 ]

Introduction to ROS-2 and Its Capabilities

Chapter 2

Rviz is the exact same as how it was defined in ROS-1. The following table shows the
features that have currently been ported from ros-visualization/rviz to ros2/rviz:
Fluid Pressure
Grid Cells
Laser Scan
Marker Array
Point Cloud (1 and 2)
Pose Array
Relative Humidity
Robot Model

Move Camera
Focus Camera
2D Nav Goal
Publish Point
Initial Pose

View controller
XY Orbit
First Person
Third Person Follower
Top-Down Orthographic

Tool Properties

Other features that are yet to be ported include image transport filters, filtering of topic lists
by topic type, message filters, and the features shown in the following list:


Interactive Marker
Pose With Covariance


[ 55 ]


Introduction to ROS-2 and Its Capabilities

Chapter 2

You can find more information about these features here: http:/​/​wiki.​ros.​org/​rviz/
DisplayTypes. A simple default Rviz2 window looks follows:

Rviz2 visualizer

Now, let's move on to the next tool, which is Rqt.

Like in ROS-1, the rqt console is available in ROS-2 as well. Most of the plugins from
ROS-1 rqt are ported and reused in ROS-2 rqt. You can find an available list of plugins
here: http:/​/​wiki.​ros.​org/​rqt/​Plugins. Some of the notable advantages of rqt are as
There's a GUI console, which is interactive and controls process startup and
shutdown states.
More than one widget can be docked in one window.

[ 56 ]

Introduction to ROS-2 and Its Capabilities

Chapter 2

You can use already available Qt plugins and convert them into custom rqt
It supports multiple languages (such as Python and C++) and multiple platforms
(on which ROS runs).
Now, let's learn how to install ROS-2 since we have basic knowledge of the ROS-2 client
libraries and tools and have covered ROS-2 fundamentals.

Installing ROS-2
In the previous chapter, we used the package manager to set up the ROS-1 environment,
desktop, pull keys, and startup installation. ROS-2 is no different and the same method can
be followed (but obviously using different setup keys and commands). However, unlike
ROS-1, where we followed the Debian package installation technique, we will try the
source installation technique in this chapter for installing ROS-2, although you can use the
Debian package installation technique as well. It is best to build ROS-2 manually on Linux
(that is, via source installation) so that we can add any new changes or releases directly into
the package and compile them. Let's get started with the source installation.

Getting started with the installation
The ROS distro we would like to install is Dashing Diademata, code-named dashing, and it
will be installed in Ubuntu 18.04 (our setup). You can find out more about how to install
ROS-2 at https:/​/​index.​ros.​org/​doc/​ros2/​Installation/​. To get started with the
installation from the source, let's set up the environment.

Setting up the system locale
You need to ensure your environment supports the UTF-8 format. If you're in Docker, the
environment will be set to POSIX. Set the locale to the specified format using the following
$ sudo locale-gen en_US en_US.UTF-8
$ sudo update-locale LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8
$ export LANG=en_US.UTF-8

[ 57 ]

Introduction to ROS-2 and Its Capabilities

Chapter 2

If all went well you should see the following output:

Setting up the system locale

It should be fine if you're using a different UTF-8 supported locale.

Adding ROS-2 repositories
Let's follow these steps to add ROS-2 repositories:
1. Ensure that you have added ROS-2 apt repositories to your system. You will
need to authorize their keys with the package manager using the following
$ sudo apt update && sudo apt install curl gnupg2 lsb-release
$ curl -s
https://raw.githubusercontent.com/ros/rosdistro/master/ros.asc |
sudo apt-key add -

2. Then, add the repository to your sources list using the following command:
$ sudo sh -c 'echo "deb [arch=amd64,arm64]
http://packages.ros.org/ros2/ubuntu `lsb_release -cs` main" >

Now that you have added the repositories, let's install the other necessities.

[ 58 ]

Introduction to ROS-2 and Its Capabilities

Chapter 2

Installing development and ROS tools
Follow these steps to install the ROS tools:
1. You need to install the following dependencies and tools using the package
manager using the following command:
$ sudo apt update && sudo apt install -y build-essential cmake git
python3-colcon-common-extensions python3-lark-parser python3-pip
python-rosdep python3-vcstool wget

2. Using pip3, install the packages for testing using the following command:
$ python3 -m pip install -U argcomplete flake8 flake8-blind-except
flake8-builtins flake8-class-newline flake8-comprehensions flake8deprecated flake8-docstrings flake8-import-order flake8-quotes
pytest-repeat pytest-rerunfailures pytest pytest-cov pytest-runner

3. Install the FAST-RTPS dependencies using the following command:
$ sudo apt install --no-install-recommends -y libasio-dev

Now that all of the dependencies and tools are installed, let's move on to creating and
building our workspace.

Getting the ROS-2 source code
We need to create a workspace and clone the ROS-2 repository into it. You can do this
using the following commands:
$ mkdir -p ~/ros2_ws/src
$ cd ~/ros2_ws
$ wget

[ 59 ]

Introduction to ROS-2 and Its Capabilities

Chapter 2

The output would be ros2.repos being saved, as shown here:

Getting the latest repositories

If you're an advanced user and would like to use the developmental release, simply replace
release-latest with master in the preceding command. If you would like to continue
experimenting, the best suggestion is to use the preceding command as is because the
preceding tree would have gone through intense testing before release. The last step would
be to import the repository information using the following command:
$ vcs import src < ros2.repos

Now that the workspace is set, let's install the dependencies.

Installing dependencies usi