38
Introduction to Robot Operating System National University of Singapore EE5111 Selected Topics in Industrial Control & Instrumentation EE5061 Industrial Control and Programming Tan Kok Kiong

Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

Introduction to

Robot Operating System

National University of SingaporeEE5111

Selected Topics in Industrial Control & InstrumentationEE5061

Industrial Control and ProgrammingTan Kok Kiong

Page 2: Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

Contents

1 Introduction to ROS 11.1 What is the ROS . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

1.1.1 What is Meta-Operating System? . . . . . . . . . . . . . . 11.1.2 Advantages and Disadvantages . . . . . . . . . . . . . . . 21.1.3 Objectives of ROS . . . . . . . . . . . . . . . . . . . . . . 2

1.2 What is ROS File System? . . . . . . . . . . . . . . . . . . . . . 31.2.1 File System Tools . . . . . . . . . . . . . . . . . . . . . . 31.2.2 Package Tools . . . . . . . . . . . . . . . . . . . . . . . . . 41.2.3 Editing the Package Configuration File (package.xml) . . 51.2.4 Editing the Build Configuration File (CMakeLists.txt) . . 51.2.5 Writing Source Code . . . . . . . . . . . . . . . . . . . . . 6

1.3 Important Concepts . . . . . . . . . . . . . . . . . . . . . . . . . 101.3.1 Overall Concepts . . . . . . . . . . . . . . . . . . . . . . . 101.3.2 Message Communication . . . . . . . . . . . . . . . . . . . 11

2 ROS Application 182.1 ROS GUI Development Tool . . . . . . . . . . . . . . . . . . . . 18

2.1.1 rqt Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . 182.1.2 Design GUI . . . . . . . . . . . . . . . . . . . . . . . . . . 20

2.2 ROS Supported by MATLAB and LabVIEW . . . . . . . . . . . 242.2.1 ROS in LabVIEW . . . . . . . . . . . . . . . . . . . . . . 24

2.3 Inverted Pendulum Application (Inverted Pendulum) . . . . . . . 252.4 DC Motor Application (DC Motor) . . . . . . . . . . . . . . . . . 28

3 Questions to Be Answered in Report 323.1 Reactor Vessel Exercise . . . . . . . . . . . . . . . . . . . . . . . 323.2 Some Questions for ROS . . . . . . . . . . . . . . . . . . . . . . . 35

I

Page 3: Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

Chapter 1

Introduction to ROS

1.1 What is the ROS

ROS is an open-source, meta-operating system for your robot. It providesthe services you would expect from an operating system, including hardwareabstraction, low-level device control, implementation of commonly-used func-tionality, message-passing between processes, and package management. It alsoprovides tools and libraries for obtaining, building, writing, and running codeacross multiple computers. Figure 1.1 is the logo of ROS.

Figure 1.1: ROS Logo

1.1.1 What is Meta-Operating System?

There are many kinds of operating systems. The most commonly used operatingsystems like Windows and Linux are general purpose operating systems.When we talk about industrial applications, real-time operating systems arewidely used.

However, a more accurate description would be that ROS is a Meta-OperatingSystem. It describes a system that performs processes such as scheduling, load-ing, monitoring and error handling by utilizing virtualization layer betweenapplications and distributed computing resources.

1

Page 4: Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

1.1.2 Advantages and Disadvantages

ROS is an open-source project, which means everyone can make contributions,and for now, it has a certain influence. Many well known industrial robot compa-nies such as ABB and KUKA are supporting ROS (KUKA-ROS and ABB-ROSPackages). Besides, mathematic softwares like MATLAB and LabVIEW alsoare supporting ROS, which means that it is pretty easy to test your own controlalgorithms with the help of MATLAB and KUKA-ROS via the ROS interface.

Apart from many platforms supporting ROS, ROS also supports different kindsof programming language like C++ and Python. A prototype model can beeasily completed with the help of ROS with any commonly used programminglanguages.

Many GUI tools are also convenient to use in ROS. We can visualize the trackof a virtual moving vehicle and we can even simulate gravity and friction withthe help of ROS.

However, ROS is always based on general purpose operating systems. Thiskind of operating systems is not designed for industrial purpose so the mostof them are not real time, which means ROS also is not real time for controlalgorithms.

1.1.3 Objectives of ROS

The primary goal of ROS is to support code reuse in robotics research and devel-opment. ROS is a distributed framework of processes that enables executablesto be individually designed and loosely coupled at runtime. These processescan be grouped into Packages and Stacks, which can be easily shared and dis-tributed. ROS also supports a federated system of code Repositories that enablecollaboration to be distributed as well. This design, from the filesystem levelto the community level, enables independent decisions about development andimplementation, but all can be brought together with ROS infrastructure tools.

In support of this primary goal of sharing and collaboration, there are severalother goals of the ROS framework:

1. Thin: ROS is designed to be as thin as possible.

2. ROS-agnostic libraries: the preferred development model is to write ROS-agnostic libraries with clean functional interfaces.

3. Language independence: the ROS framework is easy to implement in anymodern programming language.

4. Easy testing: ROS has a builtin unit/integration test framework calledrostest that makes it easy to bring up and tear down test fixtures.

5. Scaling: ROS is appropriate for large runtime systems and for large de-velopment processes.

2

Page 5: Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

1.2 What is ROS File System?

ROS file system is about how ROS can organize code files and executable files.Now we will introduce four basic concepts.

*Packages: Packages are the software organization unit of ROS code. Eachpackage can contain libraries, executables, scripts, or other artifacts.

*Manifests (package.xml): A manifest is a description of a package. It servesto define dependencies between packages and to capture meta informationabout the package like version, maintainer, license, etc...

*Workspace: Workspace is a folder including many different packages. Youcan create a workspace wherever you want.

*Catkin: catkin packages can be built as a standalone project, in the sameway that normal cmake projects can be built, but catkin also providesthe concept of workspaces, where you can build multiple, interdependentpackages together all at once.

1.2.1 File System Tools

Usually code is spread across many ROS packages. Navigating with Linuxcommand-line tools such as “ls” and “cd” can be very tedious which is whyROS provides tools to help you.

*rospack: rospack allows you to get information about packages.

*roscd: roscd is part of the rosbash suite. It allows you to change directory(cd) directly to a package or a stack.

*rosls: rosls is part of the rosbash suite. It allows you to ls directly in a packageby name rather than by absolute path.

Figure 1.2: “rospack list” Command Result

3

Page 6: Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

1.2.2 Package Tools

*catkin make: “catkin make” is a convenient tool for building codes in thecatkin workspace.

*catkin create pkg: “catkin create pkg” command creates a package folderthat contains the ‘CMakeLists.txt’ and ‘package.xml’ files necessary forthe Cake build system.

*catkin create qt pkg: “catkin create qt pkg” is used to create a Qt tem-plate package. For this lab, we will use Qt Integrated Development Envi-ronment(IDE). Qt can be easily used to design the user interface(UI) andQt creator is friendly used to organize a large project.

Example 1.2.1: Initializing a workspace

$ mkdir ˜/Desktop/‘Your Name’ ws$ cd ˜/Desktop/‘Your Name’ ws$ mkdir src$ catkin make

The above commands can build any package located in /Desktop/‘Your Name’ ws/src.This is an empty folder. No package will be built. But the workspace will beinitialized properly.

Example 1.2.2: Creating a package

$ cd ˜/Desktop/‘Your Name’ ws/src$ catkin create pkg first ros pkg std msgs roscpp

The above commands will create a package located in /Desktop/‘Your Name’ ws/src.The name of the package is “first ros pkg”, which depends on “std msgs” and“roscpp” packages.

4

Page 7: Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

Example 1.2.3: Open package with Qt Creator (Figure 1.3)

1. Double Click Qt Creator on the Destop2. File� New File or Project� Other Project� Ros Workspace3. Name: ‘Your Name’ ws

Workspace Path: Browse ‘Your Name’ ws on Desktop4. Next� Finish

Figure 1.3: Create ROS Workspace with Qt

Then you can find your first package in src folder. You can also edit everydocument under your workspace with Qt.

1.2.3 Editing the Package Configuration File (package.xml)

‘Package.xml’, which is one of the most essential ROS configuration files, isan XML file containing information about the package, including the packagename, author, license, and dependent packages. Descriptions of each statementcan be found from the ROS website.[1]

In this tutorial, we will not make any changes to this file.

1.2.4 Editing the Build Configuration File (CMakeLists.txt)

Catkin, the build system for ROS, uses CMake and describes the build environ-ment in the ‘CMakeLists.txt’ in the package folder. It configures the executablefile creation, dependency package priority build, link creation, and so on.

You may see two files with the same name “CMakeLists.txt”. One is in yourworkspace folder and another is in your first package folder. The former is forthe whole workspace compiling and the latter is for the package setting. weneed to edit the latter to complete the compiling.

5

Page 8: Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

Example 1.2.4: Editing CMakeLists.txt (Figure. 1.4)

1. Double Click ‘CMakeLists.txt’ in ‘first ros pkg’ in Qt Creator2. Add the following commands at the end of the file

Figure 1.4: Add at the End of CMakeLists.txt

The first line tells the compiler where to find the include files. The second lineintroduces the executable files and the last line shows the dependencies of theexecutable application.

1.2.5 Writing Source Code

As we know, ‘add executable’ mentioned above creates the executable ‘first ros pkg’by referring to the ‘main.cpp’ source code in the ‘src’ folder of the package. As‘main.cpp’ source code has to be manually created and written by the program-mer, let’s try a simple example to have a deeper understanding.

Example 1.2.5: Prepare for Writing Source Code

1. Expand ‘src’ in ‘Your Name’ ws in the left of Qt Creator2. Expand ‘first ros pkg’3. Right click ‘first ros pkg’4. Add New...5. C++ � C++ Source File6. Name: ‘main’; Path: Browse � Double Click ‘src’ � Open7. Next � Finish8. Double click ‘main.cpp’ in ‘first ros pkg’ � src9. Write codes

You have done all preparation works for writing your first ROS application.Now we are going to test if we have done the preparation properly. Write thefollowing code in “main.cpp”.

6

Page 9: Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

Example 1.2.6: Writing Source Code

1 #include <ros/ros.h>2 int main(int argc, char **argv)3 {4 ros::init(argc, argv, ”hello world node”);5 ros::NodeHandle nh;6 ros::Rate loop rate(10);7 int count = 0;8 while (ros::ok())9 {

10 ROS INFO(”Hello World!%d”, count);11 ros::spinOnce();12 loop rate.sleep();13 count++;14 }15 return 0;16 }

This is a very simple and fundamental ROS code written in C++.

Line 4 “ros::init()” function needs to see argc and argv so that it can performany ROS arguments and name remapping that were provided at the commandline. argc and argv mean arguments when you start an application. e.g. youenter “rospack list” in terminal. “list” is the argument for “rospack” applica-tion. For program re-mappings, you can use a different “init()” which takesremappings directly, but for most command-line programs, passing argc andargv is the easiest way to do it. The third argument to “init()” is the name ofthe node. You must call one of the “ros::init()” before using any other part ofthe ROS system.

Line 5 “NodeHandle” is the main access point to communications with theROS system. The first NodeHandle constructed will fully initialize this node,and the last NodeHandle destructed will close down the node. Although weinitialize a NodeHandle here, we do not use it.

Line 6 A “ros::Rate” object allows you to specify a frequency that you wouldlike to loop at. It will keep track of how long it has been since the last call to“Rate::sleep()”, and sleep for the correct amount of time. In this case, we tellit we want to run at 10Hz.

For the while loop in line 8, by default, roscpp will install a SIGINT handlerwhich provides Ctrl-C handling which will cause “ros::ok()” to return false ifthat happens. “ros::ok()” will return false if:

1. A SIGINT is received (Ctrl-C)

2. We have been kicked off the network by another node with the same name

7

Page 10: Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

3. ros::shutdown() has been called by another part of the application.

4. All ros::NodeHandles have been destroyed

Once “ros::ok()” returns false, all ROS calls will fail.

Then we start a loop and use function ROS INFO to print.

For Line 11, Calling “ros::spinOnce()” here is not necessary for this simpleprogram, because we are not receiving any callbacks. However, if you were toadd a subscription into this application, and do not have “ros::spinOnce()” here,the callbacks will not be called. So, add it for good measure.

Now we can build your first ROS application. Click the hammer icon (Figure.1.5) in the lower left of the IDE. Wait for the completion of the build and thenwe will do some settings to run your application.

Figure 1.5: Build Icon in Qt

8

Page 11: Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

Example 1.2.7: Runing (Figure. 1.6)

1. Click ‘Projects’ on the left hand toolbar2. In ‘Build & Run’, click ‘‘run’’3. Add Run Step � ROS Run Step � Package: ‘first ros pkg’ � ‘

first ros pkg’4. Click Edit on the left hand toolbar5. Press Ctrl+Alt+T to run a Linux Termal6. Enter ‘roscore’ and then press ‘‘Enter’’ button. ROS core will be

running7. Click ‘‘run’’ and you will see output ‘Hello World!’ with a number

in ROS Terminals8. If you cannot find ROS Terminal. Click the two triangles icon below

and then you will find it

Figure 1.6: Run Settings in Qt

Figure 1.7: ROS Terminal in Qt

9

Page 12: Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

1.3 Important Concepts

This section explains the most frequently used ROS terms. Use this section as aROS glossary. Many terms may be new to you, but even if there are unfamiliarterms, look over the definition and move on. You will become more familiarwith the concepts as you engage with examples and exercises. Some items haveappeared in the previous section and they will be defined here.[2]

1.3.1 Overall Concepts

Master

The master acts as a name server for node-to-node connections and messagecommunication. The command roscore is used to run the master, and if yourun the master, you can register the name of each node and get informationwhen needed. The connection between nodes and message communication suchas topics and services are impossible without the master.

When you execute ROS, the master will be configured with the URI address andport configured in the ROS MASTER URI. By default, the URI address usesthe IP address of local PC, and port number 11311, unless otherwise modified.

Node

A node refers to the smallest unit of processor running in ROS. Think of it asone executable program. ROS recommends creating one single node for eachpurpose, and it is recommended to develop for easy reusability. For example,in case of mobile robots, the program to operate the robot is broken down intospecialized functions. Specialized node is used for each function such as sensordrive, sensor data conversion, obstacle recognition, motor drive, encoder input,and navigation.

Upon startup, a node registers information such as name, message type, URI ad-dress and port number of the node. The registered node can act as a publisher,subscriber, service server or service client based on the registered information,and nodes can exchange messages using topics and services.

Package

A package is the basic unit of ROS. The ROS application is developed on apackage basis, and the package contains either a configuration file to launchother packages or nodes. The package also contains all the files necessary forrunning the package, including ROS dependency libraries for running variousprocesses, datasets, and configuration file. The number of official packages isabout 2,500 for ROS Indigo as of July 2017 and about 1,600 packages for ROSKinetic. In addition, although there could be some redundancies, there areabout 4,600 packages developed and released by users.

10

Page 13: Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

Figure 1.8: Communication between Nodes

Message

A node sends or receives data between nodes via a message. Messages arevariables such as integer, floating point, and boolean. Nested message structurethat contains another messages or an array of messages can be used in themessage.

Catkin

The catkin refers to the build system of ROS. The build system basically usesCMake (Cross Platform Make), and the build environment is described in the‘CMakeLists.txt’ file in the package folder.

Name

ROS has an abstract data type called ‘graph’ as its basic concept. This graphshows the connection relationship between each node and the relationship ofmessages (data) sent and received with arrows. To do this, messages and pa-rameters used in nodes, topics, and services in ROS all have unique names.

1.3.2 Message Communication

So far, we have only given an introduction to ROS but not yet explained indetail how ROS works. In this section, we will take a look at the core functionsand concepts of ROS.

As described before, ROS is developed in unit of nodes, which is the minimumunit of executable program that has broken down for maximum reusability.The node exchanges data with other nodes through messages forming a largeprogram as a whole. The key concept here is the message communication meth-ods among nodes. There are three different methods of exchanging messages: a

11

Page 14: Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

Table 1.1: Comparison of the Topic, Server, and Action

Type Features Description

TopicAsynchronousUnidirectional

Used when exchanging data continuously

ServiceSynchronousBi-directional

Used when request processingrequests and responds current states

ActionAsynchronousBi-directional

Used when it is difficult to use the service due tolong response times after the request or when an

intermediate feedback value is needed

topic which provides a unidirectional message transmission/ reception, a ser-vice which provides a bidirectional message request/response and an actionwhich provides a bidirectional message goal/result/feedback. In addition, theparameters used in the node can be modified from the outside of node. Thiscan also be considered as a type of message communication in the larger con-text. Message communication is illustrated in Figure 1.8 and the differences aresummarized in Table 1.1. It is important to use each topic, service, action, andparameter according to its correct purpose when programming on ROS. Herewe will talk about Topic in details and do some examples.

Topic

Communication on topic uses the same type of messages for both publisherand subscriber. The subscriber node receives the information of publisher nodecorresponding to the identical topic name registered in the master. Based onthis information, the subscriber node directly connects to the publisher node toreceive messages. For example, if the current position of the robot is generatedin the form of odometry information by calculating the encoder values of bothwheels of the mobile robot, the asynchronous odometry information can be con-tinuously transmitted in unidirectional flow using a topic message(x, y, i). Astopics are unidirectional and remain connected to continuously send or receivemessages, it is suitable for sensor data that requires publishing messages peri-odically. In addition, multiple subscribers can receive message from a publisherand vice versa. Multiple publishers and subscribers connections are available aswell.

Example 1.3.1: Prepare for Writing Topic Publisher

1. Create a package in your workspace.(tips: catkin create pkg)Name: ros topic publisherDenpendency: roscpp std msgs

2. Open ‘ros topic publisher’ with QT Creator.3. Create ‘main.cpp’ and wtrite code in this file4. Edit ‘CMakeLists.txt’ to add an executable file ‘ros topic publisher’

12

Page 15: Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

Now you have added another package into your workspace and if you build theworkspace, you will get two executable files. But you have not written anythingin the second package. We will show a very simple publisher here for topicmessage communication in ROS.

Example 1.3.2: Writng Code

1 #include ”ros/ros.h”2 #include ”std msgs/String.h”3 #include <sstream>45 int main(int argc, char **argv)6 {7 ros::init(argc, argv, ”ros topic publisher”);8 ros::NodeHandle n;9 ros::Publisher chatter pub =

10 n.advertise<std msgs::String>(”Chatter”,1000);11 ros::Rate loop rate(10);12 int count = 0;13 while(ros::ok())14 {15 std msgs::String msg;16 std::stringstream ss;17 ss<<”hello world”<<count;18 msg.data=ss.str();19 ROS INFO(”%s”,msg.data.c str());20 chatter pub.publish(msg);21 ros::spinOnce();22 loop rate.sleep();23 count++;24 }25 return 0;26 }

Most code of this program is similar to the previous one. Here, we look at line9 and line 20.

For line 9, the ‘advertise()’ function is to tell ROS that you want to publishon a given topic name. This invokes a call to the ROS master node, whichkeeps a registry of who is publishing and who is subscribing. After this adver-tise() call is made, the master node will notify anyone who is trying to subscribeto this topic name, and they will in turn negotiate a peer-to-peer connectionwith this node. ‘advertise()’ returns a Publisher object which allows you topublish messages on that topic through a call to publish(). Once all copiesof the returned Publisher object are destroyed, the topic will be automaticallyunadvertised. The second parameter to ‘advertise()’ is the size of the message

13

Page 16: Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

queue used for publishing messages. If messages are published more quicklythan we can send them, the number here specifies how many messages to bufferup before throwing some away.

The ‘publish()’ function is to send messages. The parameter is the messageobject. The type of this object must agree with the type given as a templateparameter to the advertise call, as was done in the constructor above.

Now you have finished programming. We need to do some settings and runthe application.

Example 1.3.3: Run Your Ros Application (Figure. 1.9)

1. Build the project first.2. Click Project � Click Run � Add Run Configuration� Add

Ros Run Configuration. Then we get ‘ROS Run Configuration 2’3. Add Run Step � ROS Run Step4. Package: ros topic publisher5. Target: ros topic publisher6. We rename ‘ROS Run Configuration’ to ‘first ros pkg’7. We rename ‘ROS Run Configuration2’ to ‘ros topic publisher’8. Go back to ‘Edit’9. Click ‘Debug’ lower left.10. Then you can choose which package you will run. We choose ‘

ros topic publisher’11. Click Run

Now your first ROS message communication application has been done. Butyou may wonder how we can know whether it is publishing message or not?Next, a very useful ROS tool is introduced.

Example 1.3.4: Use ROS Tools to Subscribe Topic (Figure. 1.10)

1. Ctrl+Alt+T. Open a new terminal2. $ rostopic list3. You will find ‘/Chatter’. This is the topic we created4. $ rostopic echo /Chatter5. You will receive the messages4. Ctrl+C will stop printing5. You can enter ‘rostopic’ and it will give you help for this command

We have done a publisher for ROS topic. We can go on to a subscriber.

14

Page 17: Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

Figure 1.9: Choose Which One to Run

Example 1.3.5: Prepare for Writing Topic Subscriber

1. Create a package in your workspace.Name: ros topic subscriber Denpendency: roscpp std msgs

2. Open ‘ros topic subscriber’ with Qt Creator.3. Create ‘main.cpp’ to wtrite code source4. Edit ‘CMakeLists.txt’ to add executable file ‘ros topic subscriber’

15

Page 18: Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

Figure 1.10: ROS Topic Publisher

Example 1.3.6: Writing Code

1 #include ”ros/ros.h”2 #include ”std msgs/String.h”3 void chatterCallback(const std msgs::String::ConstPtr& msg)4 {5 ROS INFO(”I heard: [%s]”, msg� data.c str());6 }7 int main(int argc, char **argv)8 {9 ros::init(argc, argv, ”ros topic subscriber”);

10 ros::NodeHandle n;11 ros::Subscriber chatter sub =12 n.subscribe(”Chatter”, 1000, chatterCallback);13 ros::spin();14 return 0;15 }

Line 12 subscribes to the chatter topic with the master. ROS will call the ‘chat-terCallback()’ function whenever a new message arrives. The second argumentis the queue size, in case we are not able to process messages fast enough. In thiscase, if the queue reaches 1000 messages, we will start discarding old messagesas new ones arrive. ‘NodeHandle::subscribe()’ returns a ‘ros::Subscriber’ object,that you must hold on to until you want to unsubscribe. When the Subscriberobject is destructed, it will automatically unsubscribe from the chatter topic.

16

Page 19: Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

Build and change the setting to run. Run the publisher first and then runthe subscriber. You can find the ROS Communication running perfectly.Again, here’s a condensed version of what’s going on:

1. Initialize the ROS system

2. Subscribe to the chatter topic

3. Spin, waiting for messages to arrive

4. When a message arrives, the ‘chatterCallback()’ function is called

17

Page 20: Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

Chapter 2

ROS Application

2.1 ROS GUI Development Tool

Apart from the commands introduced, there are various tools that can help uswhen using the ROS. We should note these GUI tools as complementary to thecommand line tools. There are quite a number of ROS tools, including the toolsthat ROS users have personally released as well. Among these tools, the oneswe will discuss in this section do not directly process a function in the ROS, butthey are greatly useful supplementary tools for programming with ROS.

2.1.1 rqt Tools

ROS provides various GUI tools for robot development. For example, there is agraphical tool that shows the hierarchy of each node as a diagram thereby show-ing the status of the current node and topic, and a plot tool that schematizesa message as a 2D graph. Starting from the ROS Fuerte version, more than 30GUI development tools have been integrated as the tool which can be used asa comprehensive GUI tool.

Not only that, but as the name suggests, rqt was developed based on Qt, whichis a crossplatform framework widely used for GUI programming, making it veryconvenient for users to freely develop and add plugins.

18

Page 21: Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

Example 2.1.1: Try rqt-graph

1. Ctrl+Alt+T to open a terminal2. A demo of ROS is used to show the powerful functions of rqt3. $ rosrun turtlesim turtlesim node4. Ctrl+Alt+T to open a new terminal5. $ rosrun turtlesim turtle teleop key6. Press direction keys to move the turtle7. Ctrl+Alt+T to open one more new terminal8. $ rqt9. Click plugins on the menus10. Introspection � Node Graph

You will see the relationships and messages flowing of these ROS packages withinrqt-graph clearly, and also we can monitor topics with rqt-topic (Figure. 2.1).

Figure 2.1: ROS rqt-topic

19

Page 22: Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

Example 2.1.2: Try rqt-topic

1. Run the ros topic publisher (run in QT Creator)2. Ctrl+Alt+T to open a terminal3. Plugins � Topics � Topic Monitor4. Expand ‘/chatter’5. Click the box before ‘/chatter’6. You can see Bandwidth and Hz within the topic monitor

2.1.2 Design GUI

In this section, we will use Qt Creator to Design Graphical User Interface (GUI).GUI is very important in the development procedure. A good GUI is convenientnot only for the users but also for the developers.

Qt is used for developing graphical user interfaces (GUIs) and multi-platformapplications that run on all major desktop platforms and most mobile or em-bedded platforms. Most GUI programs created with Qt have a native-lookinginterface, in which case Qt is classified as a widget toolkit.

ROS is supported by ROS-Qt. We can easily build applications based on ROSwith a Qt GUI.

Example 2.1.3: Create ROS-Qt Packages

1. Ctrl+Alt+T. Open a Terminal2. $ cd Desktop/‘Your Name’ ws/src3. $ catkin create qt pkg ros qt pkg4. $ cd ../5. $ catkin make6. Then you will see this package in Qt Creator7. Add another run configuration8. Run this package9. You will see a Qt GUI demo for ROS10. Click ”Use environment variables”. Click Connect11. From logging, you can check if you success in connecting to ROS

Master (Don’t forget to run roscore)

Now, Qt GUI package file system will be introduced. In Figure 2.3, we cansee there are three files in “src” folder. We did not see the “ui” folder in theprevious sections. The functions of these files will be shown in the following.

“main.cpp” file in “src” is the most familiar file for us. Double click “main.cpp”and you may be confused because there is nothing about ROS. Actually, this

20

Page 23: Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

Figure 2.2: ROS Qt Demo

file is for Qt to create the window we see in the demo. We can just ignore thisfile and go to the next.

“main window.cpp” is also a large file because all buttons and display func-tions are realized in this source file. Editing this file needs knowledge of Qt. Wejust skip it here.

“qnode.cpp” is the file for ROS. C++ is an object-oriented programming lan-guage. A large project is often programmed with the concept ”class”. You cantry to read this source but if you cannot, do not worry about it. We will tellyou which function is useful in the following section.

Double click “main window.ui”. You will see a designer for the GUI. Drag-ging and putting can be easily used to change the user interface. You can tryto move some blocks and then run again.

Now we try to see how this package runs. Double Click “main.cpp”. We see themain function of C++. This is the entrance of this application. In this function,it instantializes a QApplication Class, which is the core of Qt GUI. ‘MainWin-dow’ also be instantialized here. When the new object is created, a constructorwill be called. Now we hope to see what constructor of this MainWindow doeshere.

21

Page 24: Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

Figure 2.3: ROS Qt GUI File System

Figure 2.4: Constructor of MainWindow

Double Click “main window.cpp”. According to Figure 2.4, there are threeparts of this constructor. First, it connects signal and slot in Qt. Signal andslot are two concepts in Qt messages communication. They can be used totransfer data among different threads conveniently. It does not matter if you donot know this because they belong to Qt. You just need to know the meaningof Line 39 is that if there is a signal rosShutdown() emitted in qnode thread,the function close() in MainWindow thread will be called. Second, it read set-tings we saved in one file. Finally it checks if auto connected checkbox is checked.

Now we are going to check what happens in ‘on button connect clicked()’ func-tion that is shown in Figure. 2.5. This function will be called when the connectbutton is clicked. The most important function called here is ‘qnode.init()’ thatis shown in Figure. 2.6. It creates a new qnode here.

Here we should know qnode is inherited from QThread Class. That meansa new thread will be created after ‘start()’ function is called and this thread is

22

Page 25: Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

Figure 2.5: on button connect clicked

for ROS node to run.

Figure 2.6: QNode::init()

Here, two ‘Init()’ functions are defined with redefinition as is shown in Fig-ure. 2.7. It seems very familiar to us that initializes ROS node, create onepublisher, and then ‘start()’ function starts a new thread to run this ros node.When a new thread is created, ‘run()’ function in the class will be invoked.

23

Page 26: Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

Figure 2.7: QNode::run()

In the ‘QNode::run()’ function, we can see the familiar while loop here. Wedo the same thing as the first ‘ros topic publisher’ package does. We use logfunction instead of ‘ROS INFO’ to print our messages in textbox instead ofterminal. The ‘log()’ function is below the ‘run()’ function. it uses signal tosend messages to the ‘MainWindow’ thread. When ‘MainWindow’ receives thissignal, it will show these messages.

2.2 ROS Supported by MATLAB and LabVIEW

There are many mathematical softwares like MATLAB, Simulink and LabVIEWsupporting ROS development. Therefore, if these software is used to test newalgorithms, it will be very convenient to implement to the experiment devicesbecause ROS also supports many data acquisition platforms such as platformsdeveloped by National Instruments. Besides, many industrial robot companieslike ABB and KUKA also support ROS via their own packages. You can easilycombine them and test the new ideas.

2.2.1 ROS in LabVIEW

LabVIEW is a system engineering software for applications that requires test,measurement, and control with rapid access to hardware and data insights. Itsupports ROS with ‘ROSforLabVIEW’ plugin.

There is a LabVIEW client API for communication with ROS applications.

24

Page 27: Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

With this plugin, ‘ROSforLabVIEW’, users can program the communication oftopics and services in LabVIEW and access the Master IP. The client librarycan handle node-to-node transport negotiation and communication setup usingTCP as its transport mechanism as well as handle transport-specific serializa-tion and deserialization of messages. In addition, the client library allows thesubscription to a simulated clock, which uses the LabVIEW sense of time.

The current build of ROSforLabVIEW includes a set of VIs that establish aconnection to a Master (ROS Topic Init.vi), send or receive data from topics orservices (ROS Topic Write.vi and ROS Topic Read.vi, respectively), and codeor decode message strings.

2.3 Inverted Pendulum Application (Inverted Pen-dulum)

In this section, you need to use all you have learned in the previous sections tocontrol an inverted pendulum.

Figure 2.8: Inverted Pendulum

The inverted pendulum is driven by LabVIEW and the driver part has beendone in LabVIEW. Now we need to design a controller on another computer.Measurement data and control signal will be sent via ROS Topic message com-

25

Page 28: Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

munication. The ROS master will be run on the computer which is also thecontroller. The driver will be given to you directly.

Example 2.3.1: Open The LabVIEW Driver

1. ROS LabVIEW � ros invert pen.vi2. Menu � Window � Show Block Diagram

Figure 2.9: LabVIEW Driver

In the LabVIEW Driver, the main function is to receive control signal fromROS and measure angles from the two encoders. The first one is integratedwith the motor and the second one measures the angle of swing arm. We willdesign a ROS controller on the computer with ROS master. The controller willreceive the measurement data from LabVIEW and generate control signal witha cascade PID controller.

26

Page 29: Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

Figure 2.10: How to Test

Example 2.3.2: Open The Labview Driver

1. Copy ‘ros qt labview’ to your own workspace2. Ctrl+Alt+T. Open Terminal3. Go into the workspace folder4. $ catkin make5. Open you workspace with Qt Creator6. The only file you need to edit is ‘qnode.cpp’7. You need to do programming to control the invert pendulum8. You need to set the packages in the projects the first time you want

to run it

27

Page 30: Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

Figure 2.11: LabVIEW IP Address

Example 2.3.3: How to Test

1. Start ROS Master (You can let the ROS Master running all thetime)

2. $ ifconfig to check the ROS Master ip address3. Run the controller4. Click ‘running’ in LabVIEW5. You need to enter the IP Address in LabVIEW the first time you

run it so that it can find the ROS Master6. You need to stop and run again in Labview every time you close the

controller7. Run the controller in Qt Creator8. The two encoders are incremental encoders so you need to make the

inverted pendulum steady before you run the Labview9. For example, Run ‘ros qt labview’ � Make inverted pendulum

steady � Run LabVIEW � Start Motor in application.

2.4 DC Motor Application (DC Motor)

In this section, you need to use all you have learned in the previous sections tocontrol a DC Motor velocity.

DC motor is driven by LabVIEW. Now we need to design a controller on anothercomputer. Measurement data and control signal will be sent via ROS Topicmessage communication. The ROS master will be run on the computer whichis also the controller. The driver has been given to you.

28

Page 31: Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

Figure 2.12: DC motor

Example 2.3.1: Open The Labview Driver

1. ROS LabVIEW � ros dc motor.vi2. Menu � Window � Show Block Diagram

Figure 2.13: LabVIEW Driver

In the LabVIEW Driver, the main function is to receive the control signal fromthe ROS and measure the position from the encoder. We will design a ROScontroller on the computer with the ROS master. The controller will receivethe measurement data from LabVIEW and generate the control signal with avery simple PID controller to control the velocity of the DC motor.

29

Page 32: Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

Figure 2.14: How to Test

Figure 2.15: LabVIEW IP Address

Example 2.3.2: Open The Labview Driver

1. Copy ‘ros qt labview2’ to your own workspace2. Ctrl+Alt+T. Open Terminal3. Go into the workspace folder4. $ catkin make5. Open you workspace with Qt Creator6. The only file you need to edit is ‘qnode.cpp’7. You need to do programming to control the DC Motor8. You need to set the packages in projects the first time you want to

run

30

Page 33: Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

Example 2.3.3: How to Test

1. Start ROS Master (You can let the ROS Master running all thetime)

2. $ ifconfig to check the ROS Master ip address3. Run the controller4. Click ‘running’ in LabVIEW5. You need to enter the IP Address in LabVIEW the first time you

run it so that it can find the ROS Master6. You need to stop and run again in Labview every time you close the

controller7. Run the controller in Qt Creator8. Tune the parameters and make the DC Motor speed steady

31

Page 34: Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

Chapter 3

Questions to Be Answeredin Report

Two parts should be included in your report. The first part is about PLCprogram and the second part is some questions to be answered in your report.

3.1 Reactor Vessel Exercise

32

Page 35: Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

Reactor Vessel Exercise

Process Schematic of Reaction Vessel

The process schematic of a reaction vessel is as shown in the figure above.

A chemical process is to take place in a reaction vessel at a specific

temperature and at a specific pressure. The reaction vessel has a thermal

detector for measuring the temperature and a pressure gauge for the

pressure.

33

Page 36: Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

Temperature and pressure are regulated via the following three actuators:

Heater H

Cooling-water inlet K and

Safety valve S

The enabling conditions for the activation of the actuators are given as

follows:

Safety valve S is activated when

pressure P is too high and

temperature is too high or normal

Cooling-water inlet K is activated when

temperature is too high and

pressure P is too high or normal

Heater H is activated when

temperature is too low and

pressure P is not too high

or

pressure P is too low and

temperature is normal

As shown in the figure, we have

a pressure sensor which turns on when pressure is too high,

a pressure sensor which turns on when pressure is too low,

a temp. sensor which turns on when temp. is too high, and

a temp. sensor which turns on when temp. is too low.

You are to implement the sequence control using a PLC. Provide a

diagram showing the connection of the devices to the PLC and provide

the ladder diagram implementing the logic.

34

Page 37: Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

3.2 Some Questions for ROS

1. How can we apply ROS in industrial robot applications? You can refer toROS-Industrial and analyze some existing projects.

2. Why is ROS so popular? What do you think are the reasons? The answersare not limited to those contained in this tutorial.

3. Do you think ROS will completely unify programming of all robots, in-cluding industrial robots?

4. Attach the figures and codes of the examples to the end of your report.

35

Page 38: Introduction to Robot Operating Systemece.nus.edu.sg/mal/wp-content/uploads/2019/09/EE5111_Lab... · 2019-09-10 · document under your workspace with Qt. 1.2.3 Editing the Package

Reference

[1] Aaron Martinez and Enrique Fernndez. Learning ROS for Robotics Pro-gramming. Packt Publishing, 2013.

[2] Leon Jung Darby Lim Yoonseok Pyo, Hancheol Cho. ROS Robot Program-ming (English). ROBOTIS, 12 2017.

36