SlideShare a Scribd company logo
Effective Robotics Programming with ROS Third
Edition Anil Mahtani Luis Sanchez Enrique
Fernandez Aaron Martinez install download
https://ebookmeta.com/product/effective-robotics-programming-
with-ros-third-edition-anil-mahtani-luis-sanchez-enrique-
fernandez-aaron-martinez/
Download more ebook from https://ebookmeta.com
We believe these products will be a great fit for you. Click
the link to download now, or visit ebookmeta.com
to discover even more!
Learning ROS for Robotics Programming Second Edition
Enrique Fernandez Luis Sanchez Crespo Anil Mahtani
Aaron Martinez
https://ebookmeta.com/product/learning-ros-for-robotics-
programming-second-edition-enrique-fernandez-luis-sanchez-crespo-
anil-mahtani-aaron-martinez/
Robot Operating System (ROS) for Absolute Beginners:
Robotics Programming Made Easy Lentin Joseph
https://ebookmeta.com/product/robot-operating-system-ros-for-
absolute-beginners-robotics-programming-made-easy-lentin-joseph/
Robot Operating System (ROS) for Absolute Beginners:
Robotics Programming Made Easy 2nd Edition Lentin
Joseph
https://ebookmeta.com/product/robot-operating-system-ros-for-
absolute-beginners-robotics-programming-made-easy-2nd-edition-
lentin-joseph/
Bluebonnets and Bikers Wild Blooms Book 7 First Edition
D Lilac Wild Blooms
https://ebookmeta.com/product/bluebonnets-and-bikers-wild-blooms-
book-7-first-edition-d-lilac-wild-blooms/
Monkey with a Tool Belt and the Silly School Mystery
Chris Monroe
https://ebookmeta.com/product/monkey-with-a-tool-belt-and-the-
silly-school-mystery-chris-monroe/
Evidential Reasoning in Archaeology 1st Edition Robert
Chapman
https://ebookmeta.com/product/evidential-reasoning-in-
archaeology-1st-edition-robert-chapman/
Instant Pot Soups Nourishing Recipes for Every Season
Alexis Mersel
https://ebookmeta.com/product/instant-pot-soups-nourishing-
recipes-for-every-season-alexis-mersel-2/
Russian Central Asia 1867 1917 A Study in Colonial Rule
Richard A. Pierce
https://ebookmeta.com/product/russian-central-
asia-1867-1917-a-study-in-colonial-rule-richard-a-pierce/
The Norton Anthology of American Literature Volume 2
Robert S. Levine
https://ebookmeta.com/product/the-norton-anthology-of-american-
literature-volume-2-robert-s-levine/
Ironmaking and Steelmaking Zushu Li Claire Davis
https://ebookmeta.com/product/ironmaking-and-steelmaking-zushu-
li-claire-davis/
Effective Robotics Programming with ROS Third Edition Anil Mahtani Luis Sanchez Enrique Fernandez Aaron Martinez
Table of Contents
Effective Robotics Programming with ROS Third Edition
Credits
About the Authors
About the Reviewer
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
Customer Feedback
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
1. Getting Started with ROS
PC installation
Installing ROS Kinetic using repositories
Configuring your Ubuntu repositories
Setting up your source.list file
Setting up your keys
Installing ROS
Initializing rosdep
Setting up the environment
Getting rosinstall
How to install VirtualBox and Ubuntu
Downloading VirtualBox
Creating the virtual machine
Using ROS from a Docker image
Installing Docker
Getting and using ROS Docker images and containers
Installing ROS in BeagleBone Black
Prerequisites
Setting up the local machine and source.list file
Setting up your keys
Installing the ROS packages
Initializing rosdep for ROS
Setting up the environment in the BeagleBone Black
Getting rosinstall for BeagleBone Black
Basic ROS example on the BeagleBone Black
Summary
2. ROS Architecture and Concepts
Understanding the ROS Filesystem level
The workspace
Packages
Metapackages
Messages
Services
Understanding the ROS Computation Graph level
Nodes and nodelets
Topics
Services
Messages
Bags
The ROS master
Parameter Server
Understanding the ROS Community level
Tutorials to practise with ROS
Navigating through the ROS filesystem
Creating our own workspace
Creating an ROS package and metapackage
Building an ROS package
Playing with ROS nodes
Learning how to interact with topics
Learning how to use services
Using Parameter Server
Creating nodes
Building the node
Creating msg and srv files
Using the new srv and msg files
The launch file
Dynamic parameters
Summary
3. Visualization and Debugging Tools
Debugging ROS nodes
Using the GDB debugger with ROS nodes
Attaching a node to GDB while launching ROS
Profiling a node with valgrind while launching ROS
Enabling core dumps for ROS nodes
Logging messages
Outputting logging messages
Setting the debug message level
Configuring the debugging level of a particular node
Giving names to messages
Conditional and filtered messages
Showing messages once, throttling, and other combinations
Using rqt_console and rqt_logger_level to modify the logging
level on the fly
Inspecting the system
Inspecting the node's graph online with rqt_graph
Setting dynamic parameters
Dealing with the unexpected
Visualizing nodes diagnostics
Plotting scalar data
Creating a time series plot with rqt_plot
Image visualization
Visualizing a single image
3D visualization
Visualizing data in a 3D world using rqt_rviz
The relationship between topics and frames
Visualizing frame transformations
Saving and playing back data
What is a bag file?
Recording data in a bag file with rosbag
Playing back a bag file
Inspecting all the topics and messages in a bag file
Using the rqt_gui and rqt plugins
Summary
4. 3D Modeling and Simulation
A 3D model of our robot in ROS
Creating our first URDF file
Explaining the file format
Watching the 3D model on rviz
Loading meshes to our models
Making our robot model movable
Physical and collision properties
Xacro – a better way to write our robot models
Using constants
Using math
Using macros
Moving the robot with code
3D modeling with SketchUp
Simulation in ROS
Using our URDF 3D model in Gazebo
Adding sensors to Gazebo
Loading and using a map in Gazebo
Moving the robot in Gazebo
Summary
5. The Navigation Stack – Robot Setups
The navigation stack in ROS
Creating transforms
Creating a broadcaster
Creating a listener
Watching the transformation tree
Publishing sensor information
Creating the laser node
Publishing odometry information
How Gazebo creates the odometry
Using Gazebo to create the odometry
Creating our own odometry
Creating a base controller
Creating our base controller
Creating a map with ROS
Saving the map using map_server
Loading the map using map_server
Summary
6. The Navigation Stack – Beyond Setups
Creating a package
Creating a robot configuration
Configuring the costmaps – global_costmap and local_costmap
Configuring the common parameters
Configuring the global costmap
Configuring the local costmap
Base local planner configuration
Creating a launch file for the navigation stack
Setting up rviz for the navigation stack
The 2D pose estimate
The 2D nav goal
The static map
The particle cloud
The robot's footprint
The local costmap
The global costmap
The global plan
The local plan
The planner plan
The current goal
Adaptive Monte Carlo Localization
Modifying parameters with rqt_reconfigure
Avoiding obstacles
Sending goals
Summary
7. Manipulation with MoveIt!
The MoveIt! architecture
Motion planning
The planning scene
World geometry monitor
Kinematics
Collision checking
Integrating an arm in MoveIt!
What's in the box?
Generating a MoveIt! package with the Setup Assistant
Integration into RViz
Integration into Gazebo or a real robotic arm
Simple motion planning
Planning a single goal
Planning a random target
Planning a predefined group state
Displaying the target motion
Motion planning with collisions
Adding objects to the planning scene
Removing objects from the planning scene
Motion planning with point clouds
The pick and place task
The planning scene
The target object to grasp
The support surface
Perception
Grasping
The pickup action
The place action
The demo mode
Simulation in Gazebo
Summary
8. Using Sensors and Actuators with ROS
Using a joystick or a gamepad
How does joy_node send joystick movements?
Using joystick data to move our robot model
Using Arduino to add sensors and actuators
Creating an example program to use Arduino
Robot platform controlled by ROS and Arduino
Connecting your robot motors to ROS using Arduino
Connecting encoders to your robot
Controlling the wheel velocity
Using a low-cost IMU – 9 degrees of freedom
Installing Razor IMU ROS library
How does Razor send data in ROS?
Creating an ROS node to use data from the 9DoF sensor in our
robot
Using robot localization to fuse sensor data in your robot
Using the IMU – Xsens MTi
How does Xsens send data in ROS?
Using a GPS system
How GPS sends messages
Creating an example project to use GPS
Using a laser rangefinder – Hokuyo URG-04lx
Understanding how the laser sends data in ROS
Accessing the laser data and modifying it
Creating a launch file
Using the Kinect sensor to view objects in 3D
How does Kinect send data from the sensors, and how do we
see it?
Creating an example to use Kinect
Using servomotors – Dynamixel
How does Dynamixel send and receive commands for the
movements?
Creating an example to use the servomotor
Summary
9. Computer Vision
ROS camera drivers support
FireWire IEEE1394 cameras
USB cameras
Making your own USB camera driver with OpenCV
ROS images
Publishing images with ImageTransport
OpenCV in ROS
Installing OpenCV 3.0
Using OpenCV in ROS
Visualizing the camera input images with rqt_image_view
Camera calibration
How to calibrate a camera
Stereo calibration
The ROS image pipeline
Image pipeline for stereo cameras
ROS packages useful for Computer Vision tasks
Visual odometry
Using visual odometry with viso2
Camera pose calibration
Running the viso2 online demo
Performing visual odometry with viso2 with a stereo camera
Performing visual odometry with an RGBD camera
Installing fovis
Using fovis with the Kinect RGBD camera
Computing the homography of two images
Summary
10. Point Clouds
Understanding the Point Cloud Library
Different point cloud types
Algorithms in PCL
The PCL interface for ROS
My first PCL program
Creating point clouds
Loading and saving point clouds to the disk
Visualizing point clouds
Filtering and downsampling
Registration and matching
Partitioning point clouds
Segmentation
Summary
Index
Effective Robotics
Programming with ROS Third
Edition
Effective Robotics
Programming with ROS Third
Edition
Copyright © 2016 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, and its dealers
and distributors will be held liable for any damages caused or
alleged to be 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.
First published: September 2013
Second edition: August 2015
Third edition: December 2016
Production reference: 1231216
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78646-365-4
www.packtpub.com
Credits
Authors
Anil Mahtani
Luis Sánchez
Enrique Fernández
Aaron Martinez
Reviewer
Lentin Joseph
Commissioning Editor
Kartikey Pandey
Acquisition Editor
Narsimha Pai
Content Development Editor
Abhishek Jadhav
Technical Editor
Gaurav Suri
Copy Editors
Safis Editing
Dipti Mankame
Project Coordinator
Judie Jose
Proofreader
Safis Editing
Indexer
Pratik Shirodkar
Graphics
Kirk D'Penha
Production Coordinator
Shantanu N. Zagade
Cover Work
Shantanu N. Zagade
About the Authors
Anil Mahtani is a computer scientist who has dedicated an
important part of his career to underwater robotics. He first started
working in the field with his master thesis, where he developed a
software architecture for a low-cost ROV. During the development of
his thesis, he also became the team leader and lead developer of
AVORA, a team of university students that designed and developed
an autonomous underwater vehicle for the Students Autonomous
Underwater Challenge – Europe (SAUC-E) in 2012. That same year,
Anil Mahtani completed his thesis and his MSc in Computer Science
at the University of Las Palmas de Gran Canaria and then became a
Software Engineer at SeeByte Ltd, a world leader in smart software
solutions for underwater systems. In 2015, he joined Dell
Secureworks as a Software Engineer, where he applies his
knowledge and skills toward developing intrusion detection and
prevention systems.
During his time at SeeByte Ltd, Anil Mahtani played a key role in the
development of several semi-autonomous and autonomous
underwater systems for the military and oil and gas industries. In
those projects, he was heavily involved in the development of
autonomy systems, the design of distributed software architectures,
and low-level software development and also contributed in
providing Computer Vision solutions for front-looking sonar imagery.
At SeeByte Ltd, he also achieved the position of project manager,
managing a team of engineers developing and maintaining the
internal core C++ libraries.
His professional interests lie mainly in software engineering,
algorithms, data structures, distributed systems, networks, and
operating systems. Anil's main role in robotics is to provide efficient
and robust software solutions, addressing not only the current
problems at hand but also foreseeing future problems or possible
enhancements. Given his experience, he is also an asset when
dealing with Computer Vision, machine learning, or control
problems. Anil has also interests in DIY and electronics, and he has
developed several Arduino libraries, which he has contributed back
to the community.
First of all, I would like to thank my family and friends for their
support and for always being there when I needed them. I would
also like to thank my girlfriend Alex for her support and patience,
and for being a constant source of inspiration. Finally, I would
like to thank my colleagues Ihor Bilyy and Dan Good, who have
taught me a lot, both personally and professionally, during these
new steps in my career as a software engineer.
Luis Sánchez has completed his dual master's degree in electronics
and telecommunication engineering at the University of Las Palmas
de Gran Canaria.
He has collaborated with different research groups as the Institute
for Technological Development and Innovation (IDETIC), the
Oceanic Platform of Canary Islands (PLOCAN), and the Institute of
Applied Microelectronics (IUMA) where he actually researches on
imaging super-resolution algorithms.
His professional interests lie in Computer Vision, signal processing,
and electronic design applied on robotics systems. For this reason,
he joined the AVORA team, a group of young engineers and
students working on the development of Underwater Autonomous
Vehicles (AUV) from scratch. Inside this project, Luis has started
developing acoustic and Computer Vision systems, extracting
information from different sensors such as hydrophones, sonar, or
camera.
With a strong background gained in marine technology, Luis
cofounded Subsea Mechatronics, a young start-up, where he works
on developing remotely operated and autonomous vehicles for
underwater environments.
Here's what Dario Sosa Cabrera, a marine technologies engineer and
entrepreneur (and the cofounder and maker of LPA Fabrika: Gran
Canaria Maker Space) has to say about Luis:
"He is very enthusiastic and an engineer in multiple disciplines. He is
responsible for his work. He can manage himself and can take up
responsibilities as a team leader, as demonstrated at the euRathlon
competition. His background in electronics and telecommunications
allows him to cover a wide range of expertise from signal processing
and software, to electronic design and fabrication."
Luis has participated as a technical reviewer of the previous version
of Learning ROS for Robotics Programming and as a cowriter of the
second edition.
First, I have to acknowledge Aaron, Anil, and Enrique for inviting
me to participate in this book. It has been a pleasure to return to
work with them. Also, I want to thank the Subsea Mechatronics
team for the great experience working with heavy underwater
robots, we grew together during these years. I have to mention
LPA Fabrika – Gran Canaria Maker Space for the enthusiasm
preparing and teaching educational robotics and technological
projects; sharing a workspace with kids can be really motivating.
Finally, I will have to thank my family and my girlfriend for the
big support and encouragement in every project where I'm
involved. I want to dedicate my contribution in this book to
them.
Enrique Fernández has a PhD in computer engineering and an
extensive background in robotics. His PhD thesis addressed the
problem of Path Planning for Autonomous Underwater Gliders, but
he also worked on other robotics projects, including SLAM,
perception, vision, and control. During his doctorate, he joined the
Center of Underwater Robotics Research in the University of Girona,
where he developed Visual SLAM and INS modules in ROS for
Autonomous Underwater Vehicles (AUVs), and participated in the
Student Autonomous Underwater Challenge, Europe (SAUC-E) in
2012, and collaborated in the 2013 edition; in 2012, he was awarded
a prize.
During his PhD, Enrique published several conference papers and
publications to top robotics conferences, such as the International
Conference of Robotics and Automation (ICRA). He has also
authored some book chapters and ROS books.
Later, Enrique joined PAL Robotics as a SLAM engineer in June 2013.
There he worked with the REEM and REEM-C humanoid robots using
ROS software and also contributed to the open source community,
mainly to ROS Control repository, being one of the maintainers
nowadays. In 2015, he joined Clearpath Robotics to work on the
Autonomy team, developing perception algorithms. He has worked
on the software that runs on the industrial mobile robots OTTO 1500
and OTTO 100, which has been deployed into the facilities of
multiple large industry companies, such as General Electric and John
Deere.
I would like to thank the coauthors of the book for their
dedication. I also want to say thanks to the members of my
research group in Las Palmas de Gran Canaria and the Center of
Underwater Robotics Research in Girona. I learned a lot about
robotics then, and I started to work with ROS. Thanks also to the
ex-colleagues from PAL Robotics, who received me with open
hands, and have given me the opportunity to learn even more
from ROS and (humanoid) robots. Last by not least, to my
current colleagues at Clearpath Robotics, where I have mastered
ROS and contributed to the software that runs 24/7 in the self-
driving robots we have sold for the Industry 4.0. Finally, thanks
to my family and friends for their help and support, especially
Eva.
Aaron Martinez is a computer engineer, entrepreneur, and expert
in digital fabrication. He did his master's thesis in 2010 at the IUCTC
(Instituto Universitario de Ciencias y Tecnologias Ciberneticas) in the
University of Las Palmas de Gran Canaria. He prepared his master's
thesis in the field of telepresence using immersive devices and
robotic platforms. After completing his academic career, he attended
an internship program at The Institute for Robotics in the Johannes
Kepler University in Linz, Austria. During his internship program, he
worked as part of a development team of a mobile platform using
ROS and the navigation stack. After that, he was involved in some
projects related to robotics; one of them is the AVORA project in the
University of Las Palmas de Gran Canaria. In this project, he worked
on the creation of an AUV to participate in the Student Autonomous
Underwater Challenge-Europe (SAUC-E) in Italy. In 2012, he was
responsible for manufacturing this project; in 2013, he helped to
adapt the navigation stack and other algorithms from ROS to the
robotic platform.
Recently, Aaron created his own company named
SubSeaMechatronics, SL. This company works with projects related
with underwater robotics and telecontrol systems. They are also
designing and manufacturing subsea sensors. The company
manufactures devices for other companies and research and
development institutes.
Aaron has experience in many fields, such as programming, robotics,
mechatronics, and digital fabrication as well as many devices, such
as Arduino, BeagleBone, Servers, and LIDAR, and nowadays he is
designing in SubSeaMechatronics SL some robotics platforms for
underwater and aerial environments.
I would like to thank my girlfriend who has supported me while
writing this book and gave me motivation to continue growing
professionally. I also want to thank Donato Monopoli, Head of
Biomedical Engineering Department at ITC (Canary-Islands
Institute of Technology), and all the staff there. Thanks for
teaching me all I know about digital fabrication, machinery, and
engineering tissue. I spent the best years of my life in your
workshop.
Thanks to my colleagues in the university, especially Alexis
Quesada, who gave me the opportunity to create my first robot
in my master's thesis. I have learned a lot about robotics working
with them.
Finally, thanks to my family and friends for their help and
support.
About the Reviewer
Lentin Joseph is an author, entrepreneur, electronics engineer,
robotics enthusiast, machine vision expert, embedded programmer,
and the founder and CEO of Qbotics Labs
(http://www.qboticslabs.com) in India.
He completed his bachelor's degree in electronics and
communication engineering at the Federal Institute of Science and
Technology (FISAT), Kerala. For his final year engineering project, he
made a social robot that can interact with people
(http://www.technolabsz.com/2012/07/social-robot-my-final-
year.html). The project was a huge success and was mentioned in
many forms of visual and print media. The main features of this
robot were that it can communicate with people and reply
intelligently and has some image processing capabilities, such as
face, motion, and color detection. The entire project was
implemented using the Python programming language. His interest
in robotics, image processing, and Python started with that project.
After his graduation, for 3 years he worked at a start-up company
focusing on robotics and image processing. In the meantime, he
learned famous robotic software platforms, such as Robot Operating
System (ROS), V-REP, Actin (a robotic simulation tool), and image
processing libraries, such as OpenCV, OpenNI, and PCL. He also
knows about robot 3D designing and embedded programming on
Arduino and Tiva Launchpad.
After 3 years of work experience, he started a new company named
Qbotics Labs, which mainly focuses on research to build up some
great products in domains, such as robotics and machine vision. He
maintains a personal website (http://www.lentinjoseph.com) and a
technology blog named technolabsz (http://www.technolabsz.com).
He publishes his works on his tech blog. He was also a speaker at
PyCon2013, India, on the topic Learning Robotics using Python.
Lentin is the author of the books Learning Robotics using Python
(refer to http://learn-robotics.com to find out more) and Mastering
ROS for Robotics Programming (refer to http://mastering-ros.com to
find out more) by Packt Publishing. The first book was about building
an autonomous mobile robot using ROS and OpenCV. This book was
launched in ICRA 2015 and was featured in the ROS blog, Robohub,
OpenCV, the Python website, and various other such forums. The
second book is for mastering robot operating system; this was also
launched ICRA 2016, and it is one of the best seller book in ROS.
Lentin and his team was a winner of HRATC 2016 challenge
conducted as a part of ICRA 2016, and he was Also a finalist in the
ICRA 2015 challenge, HRATC
(http://www.icra2016.org/conference/challenges/).
www.PacktPub.com
eBooks, discount offers, and
more
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.PacktPub.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.PacktPub.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 eBooks.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you
full access to all Packt books and video courses, as well as industry-
leading tools to help you plan your personal development and
advance your career.
Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Customer Feedback
Thank you for purchasing this Packt book. We take our commitment
to improving our content and products to meet your needs seriously
—that's why your feedback is so valuable. Whatever your feelings
about your purchase, please consider leaving a review on this book's
Amazon page. Not only will this help us, more importantly it will also
help others in the community to make an informed decision about
the resources that they invest in to learn.
You can also review for us on a regular basis by joining our
reviewers' club. If you're interested in joining, or would like to
learn more about the benefits we offer, please contact us:
<customerreviews@packtpub.com>.
Preface
Effective Robotics Programming with ROS, Third Edition gives you a
comprehensive review of ROS, the Robot Operating System
framework, which is used nowadays by hundreds of research groups
and companies in the robotics industry. More importantly, ROS is
also the painless entry point to robotics for nonprofessionals and
students. This book will guide you through the installation process of
ROS, and soon enough, you will be playing with the basic tools and
understanding the different elements of the framework.
The content of the book can be followed without any special devices,
and each chapter comes with a series of source code examples and
tutorials that you can run on your own computer. This is the only
thing you need to follow the book.
However, we also show you how to work with hardware so that you
can connect your algorithms with the real world. Special care has
been taken in choosing devices that are affordable for amateur
users, but at the same time, the most typical sensors or actuators in
robotics research are covered.
Finally, the potential of ROS is illustrated with the ability to work with
whole robots in a real or simulated environment. You will learn how
to create your own robot and integrate it with a simulation by using
the Gazebo simulator. From here, you will have the chance to
explore the different aspects of creating a robot, such as perceiving
the world using computer vision or point cloud analysis, navigating
through the environment using the powerful navigation stack, and
even being able to control robotic arms to interact with your
surroundings using the MoveIt! package. By the end of the book, it
is our hope that you will have a thorough understanding of the
endless possibilities that ROS gives you when developing robotic
systems.
What this book covers
Chapter 1, Getting Started with ROS, shows the easiest way you
must follow in order to have a working installation of ROS. You will
see how to install ROS on different platforms, and you will use ROS
Kinetic throughout the rest of the book. This chapter describes how
to make an installation from Debian packages, compile the sources,
and make installations in virtual machines, Docker, and ARM CPU.
Chapter 2, ROS Architecture and Concepts, is concerned with the
concepts and tools provided by the ROS framework. We will
introduce you to nodes, topics, and services, and you will also learn
how to use them. Through a series of examples, we will illustrate
how to debug a node and visualize the messages published through
a topic.
Chapter 3, Visualization and Debugging Tools, goes a step further in
order to show you powerful tools to debug your nodes and visualize
the information that goes through the node's graph along with the
topics. ROS provides a logging API that allows you to diagnose node
problems easily. In fact, we will see some powerful graphical tools,
such as rqt_console and rqt_graph, as well as visualization
interfaces, such as rqt_plot and rviz. Finally, this chapter explains
how to record and play back messages using rosbag and rqt_bag.
Chapter 4, 3D Modeling and Simulation, constitutes one of the first
steps in order to implement your own robot in ROS. It shows you
how to model a robot from scratch and run it in simulation using the
Gazebo simulator. You will simulate sensors, such as cameras and
laser range sensors. This will later allow you to use the whole
navigation stack provided by ROS and other tools.
Chapter 5, The Navigation Stack – Robot Setups, is the first of two
chapters concerned with the ROS navigation stack. This chapter
describes how to configure your robot so that it can be used with
the navigation stack. In the same way, the stack is explained, along
with several examples.
Chapter 6, The Navigation Stack – Beyond Setups, continues the
discussion of the previous chapter by showing how we can
effectively make our robot navigate autonomously. It will use the
navigation stack intensively for that. This chapter shows the great
potential of ROS using the Gazebo simulator and RViz to create a
virtual environment in which we can build a map, localize our robot,
and do path planning with obstacle avoidance.
Chapter 7, Manipulation with MoveIt!, is a set of tools for mobile
manipulation in ROS. This chapter contains the documentation that
you need to install this package. The chapter also contains example
demonstrations with robotic arms that use MoveIt! for manipulation
tasks, such as grasping, picking and placing, or simple motion
planning with inverse kinematics.
Chapter 8, Using Sensors and Actuators with ROS, literally connects
ROS with the real world. This chapter goes through a number of
common sensors and actuators that are supported in ROS, such as
range lasers, servo motors, cameras, RGB-D sensors, and GPS.
Moreover, we explain how to use embedded systems with
microcontrollers, similar to the widely known Arduino boards.
Chapter 9, Computer Vision, shows the support for cameras and
computer vision tasks in ROS. This chapter starts with drivers
available for FireWire and USB cameras so that you can connect
them to your computer and capture images. You will then be able to
calibrate your camera using the ROS calibration tools. Later, you will
be able to use the image pipeline, which is explained in detail. Then,
you will see how to use several APIs for vision and integrate
OpenCV. Finally, the installation and usage of a visual odometry
software is described.
Chapter 10, Point Clouds, shows how to use Point Cloud Library in
your ROS nodes. This chapter starts with the basics utilities, such as
read or write a PCL snippet and the conversions needed to publish or
subscribe to these messages. Then, you will create a pipeline with
different nodes to process 3D data, and you will downsample, filter,
and search for features using PCL.
What you need for this book
This book was written with the intention that almost everybody can
follow it and run the source code examples provided with it.
Basically, you need a computer with a Linux distribution. Although
any Linux distribution should be fine, it is recommended that you
use a version of Ubuntu 16.04 LTS. Then, you will use ROS Kinetic,
which is installed according to the instructions given in Chapter 1,
Getting Started with ROS.
As regards the hardware requirements of your computer, in general,
any computer or laptop is enough. However, it is advisable to use a
dedicated graphics card in order to run the Gazebo simulator. Also, it
will be good to have a good number of peripherals so that you can
connect several sensors and actuators, including cameras and
Arduino boards.
You will also need Git (the git-core Debian package) in order to clone
the repository with the source code provided with this book.
Similarly, you are expected to have a basic knowledge of the Bash
command line, GNU/Linux tools, and some C/C++ programming
skills.
Who this book is for
This book is targeted at all robotics developers, from amateurs to
professionals. It covers all the aspects involved in a whole robotic
system and shows how ROS helps with the task of making a robot
really autonomous. Anyone who is learning robotics and has heard
about ROS but has never tried it will benefit from this book. Also,
ROS beginners will learn advanced concepts and tools of this
framework. Indeed, even regular users may learn something new
from some particular chapters. Certainly, only the first three chapters
are intended for new users; so those who already use ROS can skip
these ones and go directly to the rest.
Conventions
In this book, you will find a number of text styles that distinguish
between different kinds of information. Here are some examples of
these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames,
file extensions, pathnames, dummy URLs, user input, and Twitter
handles are shown as follows: "The rosdep command-line tool must
be installed and initialized before you can use ROS."
A block of code is set as follows:
#include <ros/ros.h>
#include <dynamic_reconfigure/server.h>
#include <chapter2_tutorials/chapter2Config.h>
When we wish to draw your attention to a particular part of a code
block, the relevant lines or items are set in bold:
dynamic_reconfigure::Server<chapter2_tutorials::ch
apter2Config>::CallbackType f;
f = boost::bind(&callback, _1, _2);
Any command-line input or output is written as follows:
$ sudo apt-get install python-rosdep
$ sudo rosdep init
$ rosdep update
New terms and important words are shown in bold. Words that
you see on the screen, for example, in menus or dialog boxes,
appear in the text like this: "When it finishes, you can start your
virtual machine by clicking on the Start button."
Note
Warnings or important notes appear in a box like this.
Tip
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what
you think about this book—what you liked or disliked. Reader
feedback is important for us as it helps us develop titles that you will
really get the most out of.
To send us general feedback, simply e-mail
<feedback@packtpub.com>, and mention the book's title in the subject
of your message.
If there is a topic that you have expertise in and you are interested
in either writing or contributing to a book, see our author guide at
www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a
number of things to help you to get the most from your purchase.
Downloading the example code
You can download the example code files from your account at
http://www.packtpub.com for all the Packt Publishing books you
have purchased. If you purchased this book elsewhere, you can visit
http://www.packtpub.com/support and register to have the files e-
mailed directly to you. You can also download these code files from
https://github.com/rosbook/effective_robotics_programming_with_ro
s. The same code files are also available at
https://github.com/PacktPublishing/Effective-Robotics-Programming-
with-ROS.
Downloading the color images of
this book
We also provide you with a PDF file that has color images of the
screenshots/diagrams used in this book. The color images will help
you better understand the changes in the output. You can download
this file from
https://www.packtpub.com/sites/default/files/downloads/EffectiveRo
boticsProgrammingwithROSThirdEdition_ColorImages.pdf.
Errata
Although we have taken every care to ensure the accuracy of our
content, mistakes do happen. If you find a mistake in one of our
books—maybe a mistake in the text or the code—we would be
grateful if you could report this to us. By doing so, you can save
other readers from frustration and help us improve subsequent
versions of this book. If you find any errata, please report them by
visiting http://www.packtpub.com/submit-errata, selecting your
book, clicking on the Errata Submission Form link, and entering
the details of your errata. Once your errata are verified, your
submission will be accepted and the errata will be uploaded to our
website or added to any list of existing errata under the Errata
section of that title.
To view the previously submitted errata, go to
https://www.packtpub.com/books/content/support and enter the
name of the book in the search field. The required information will
appear under the Errata section.
Piracy
Piracy of copyrighted material on the Internet is an ongoing problem
across all media. At Packt, we take the protection of our copyright
and licenses very seriously. If you come across any illegal copies of
our works in any form on the Internet, please provide us with the
location address or website name immediately so that we can
pursue a remedy.
Please contact us at <copyright@packtpub.com> with a link to the
suspected pirated material.
We appreciate your help in protecting our authors and our ability to
bring you valuable content.
Questions
If you have a problem with any aspect of this book, you can contact
us at <questions@packtpub.com>, and we will do our best to address
the problem.
Chapter 1. Getting Started
with ROS
Welcome to the first chapter of this book, where you will learn how
to install ROS, the new standard software framework in robotics.
This book is an update on Learning ROS for Robotics Programming -
Second Edition, based in ROS Hydro/Indigo. With ROS, you will learn
how to program and control your robots the easy way, using tons of
examples and source code that will show you how to use sensors
and devices, or how to add new functionalities, such as autonomous
navigation, visual perception, and others, to your robot. Thanks to
the open source ethos and a community that is developing state-of-
the-art algorithms and providing new functionalities, ROS is growing
every day.
This book will cover the following topics:
Installing ROS Kinetic framework on a compatible version of
Ubuntu
The basic operation of ROS
Debugging and visualizing data
Programming your robot using this framework
Connecting sensors, actuators, and devices to create your robot
Creating a 3D model to use in the simulator
Using the navigation stack to make your robot autonomous
In this chapter, we are going to install a full version of ROS Kinetic in
Ubuntu. ROS is fully supported and recommended for Ubuntu, and it
is experimental for other operative systems. The version used in this
book is the 15.10 (Wily Werewolf), and you can download it for free
from http://releases.ubuntu.com/15.10. Note that you can also use
Ubuntu 16.04 (Xenial), following the same steps shown here;
indeed, for the BeagleBone Black installation we will use Ubuntu
Xenial.
Before starting with the installation, we are going to learn about the
origin of ROS and its history.
The Robot Operating System (ROS) is a framework that,
nowadays, is widely accepted and used in the robotics community.
Its main goal is to make the multiple components of a robotics
system easy to develop and share so they can work on other robots
with minimal changes. This basically allows for code reuse, and
improves the quality of the code by having it tested by a large
number of users and platforms. ROS was originally developed in
2007 by the Stanford Artificial Intelligence Laboratory (SAIL)
in support of the Stanford AI Robot project. Since 2008, Willow
Garage continued the development, and recently Open Source
Robotics Foundation (OSRF) began to oversee the maintenance
of ROS and partner projects, like Gazebo, including the development
of new features.
A lot of research institutions have started to develop in ROS, adding
hardware and sharing their code. Also, companies have started to
adapt their products to be used in ROS. In the following set of
images, you can see some of the platforms that are fully supported.
Normally, these platforms are published with a lot of code,
examples, and simulators to permit the developers to start work
easily. The first three humanoid robots are examples of robots with
published code. The last one is an AUV developed by the University
of Las Palmas de Gran Canaria, and the code has not been published
yet. You can find many other examples at http://wiki.ros.org/Robots.
Most of the sensors and actuators used in robotics are supported by
ROS as drivers. Furthermore, some companies benefit from ROS and
open hardware to create cheaper and easier to use sensors, as
existing software can be used for them at zero cost. The Arduino
board is a good example because you can add many different kinds
of sensors to this cheap electronic board, such as encoders, light
and temperature sensors, and many others, and then expose their
measurements to ROS to develop robotic applications.
ROS provides a hardware abstraction, low-level device control with
ROS control, implementations of commonly used functionalities and
libraries, message passing between processes, and package
management with catkin and cmake.
It uses graph architecture with a centralized topology, where
processing takes place in nodes that may receive and send
messages to communicate with other nodes on the graph net. A
node is any process that can read data from a sensor, control an
actuator, or run high level, complex robotic or vision algorithms for
mapping or navigating autonomously in the environment.
The *-ros-pkg is a community repository for developing high-level
libraries easily. Many of the capabilities frequently associated with
ROS, such as the navigation library and the rviz visualizer, are
developed in this repository. These libraries provide a powerful set of
tools for working with ROS easily; visualization, simulators, and
debugging tools are among the most important features that they
have to offer. In the following image you can see two of these tools,
the rviz and rqt_plot. The screenshot in the center is rqt_plot,
where you can see the plotted data from some sensors. The other
two screenshots are rviz; in the screenshot you can see a 3D
representation of a real robot.
ROS is released under the terms of the Berkeley Software
Distribution (BSD) license and is an open source software. It is
free for commercial and research use. The ros-pkg contributed
packages are licensed under a variety of open source licenses.
With ROS, you can take a code from the repositories, improve it, and
share it again. This philosophy is the underlying principle of open
source software.
ROS has numerous versions, the last one being Indigo. In this book,
we are going to use Kinetic because it is the latest version. Now we
are going to show you how to install ROS Kinetic. As we mentioned
before, the operating system used in the book is Ubuntu, and we are
going to use it throughout this book and with all the tutorials. If you
use another operating system and you want to follow the book, the
best option is to install a virtual machine with a copy of Ubuntu. At
the end of this chapter, we will explain how to install a virtual
machine to use the ROS inside it, or download a virtual machine with
ROS installed.
If you want to try installing it on an operating system other than
Ubuntu, you can find instructions on how to do so with many other
operating systems at http://wiki.ros.org/kinetic/Installation.
PC installation
We assume that you have a PC with a copy of Ubuntu 15.10. It will
also be necessary to have a basic knowledge of Linux and command
tools such as the terminal, Vim, folder creation, and so on. If you
need to learn these tools, you can find a lot of relevant resources on
the Internet, or you can find books on these topics instead.
Installing ROS Kinetic using
repositories
Last year, the ROS web page was updated with a new design and a
new organization of contents. The following is a screenshot of the
web page:
In the menu, you can find information about ROS and whether ROS
is a good choice for your system. You can also find blogs, news, and
other features.
Instructions for ROS installation can be found under the Install tab
in the Getting Started section.
ROS recommends that you install the system using the repository
instead of the source code, unless you are an advanced user and
you want to make a customized installation; in that case, you may
prefer installing ROS using the source code.
To install ROS using the repositories, we will start by configuring the
Ubuntu repository in our system.
Configuring your Ubuntu
repositories
In this section, you will learn the steps for installing ROS Kinetic in
your computer. This process has been based on the official
installation page, which can be found at
http://wiki.ros.org/kinetic/Installation/Ubuntu.
We assume that you know what an Ubuntu repository is and how to
manage it. If you have any doubts about it, refer to
https://help.ubuntu.com/community/Repositories/Ubuntu.
Before we start the installation, we need to configure our
repositories. To do that, the repositories need to allow restricted,
universe, and multiverse. To check if your Ubuntu accepts these
repositories, click on Ubuntu Software Center in the menu on the
left-hand side of your desktop, as shown in the following screenshot:
Click on Edit | Software Sources and you will see the following
window. Make sure that all the listed options are checked as shown
in the following screenshot (choose the appropriate country for the
server from which you download the sources):
Normally these options are marked, so you should not have any
problem with this step.
Setting up your source.list file
In this step, you have to select your Ubuntu version. It is possible to
install ROS Kinetic in various versions of the operating system. You
can use any of them, but we recommend version 15.10 to follow the
chapters of this book. Keep in mind that Kinetic works in the Wily
Werewolf (15.10) and Xenial Xerus (16.04) versions of Ubuntu. Type
the following command to add the repositories:
sudo sh -c 'echo "deb
http://packages.ros.org/ros/ubuntu $(lsb_release -
cs) main" > /etc/apt/sources.list.d/ros-
latest.list'
Other documents randomly have
different content
lessons on hearts which are really bleeding. Let such groan at
liberty, and attempt not to contradict nature. Solitude may exalt the
imagination; but it also inspires consoling ideas. In the silence of its
refuge the desolate mourner brings himself to a nearer communion
with him he regrets. He invokes, sees, and addresses him. Grief is
more ingenious than we imagine in finding consolation, and has
learned to employ different remedies according as the wounds are
slight or deep. Two persons have each lost a dear friend. The one
studiously avoids the places where he used to meet his friend. The
other repairs to his desolate haunts, and surrounding himself by
monuments associated with his memory, he seeks, if I may so say,
to restore him to life.
The death of a beloved wife is, perhaps, the most inconsolable of
evils. Let this follow a series of other misfortunes, and it so effaces
their remembrance that the sufferer feels he has not until then
known real grief. But if this affliction be one under which our
strength is broken, let it be the only one to obtain this fatal triumph.
Under all other misfortunes we may find in ourselves resources for
sustaining them; and may invariably either evade or assuage them,
or mitigate their bitterness by resignation.
Moralists have expatiated upon the manner in which a sage ought
to contemplate the evils of life. Instead of subscribing to their trite
maxims, often more imposing than practicable, I sketch a summary
of my philosophy. I caution the feeble and erring beings that
surround me, not to dream of unmixed happiness. I invite them to
partake promptly of all innocent pleasures. The evils too often
appended to them may follow. Know nothing of those which have no
existence except in opinion. Struggle with courage to escape all that
may be evaded. But if it become inevitable to meet them, let
resignation, closing your eyes on the past, secure the repose of
patient endurance when happiness exists for you no longer.
Permit me to give these ideas some development. If I may believe
the most prevalent modern philosophy, tranquillity of mind is the
result of organization, or temperament, and of circumstances. It is
the burden of my inculcation, that it may be of our own procuring;
and that we owe it still more to the masculine exercise of our
reason, discipline, and mental energy, than to our temperament or
condition.
We have reason to deplore that unhappy being, who, yielding to
dreams of pleasure, forgets to forearm himself against a fatal
awakening. The history of great political convulsions, and, more than
all, that of the French revolution furnishes impressive examples of
this spectacle. It offers more than one instance, in the feebler sex,
of persons, who seemed created only to respire happiness. To the
advantages of youth, talent and beauty, were united the most
exalted rank, and wealth, pleasure and power, apparently to the
extent of their wishes. To the dazzling fascination, with which a
brilliant crowd surrounded their inexperience, many of them united
the richer domestic enjoyments of the wife and mother. In the midst
of their illusions, the revolutionary shout struck their ear, like a
thunderstroke. Executioners bade them ascend the scaffold.[12]
These great catastrophes, I know, are rare. But there will never
cease to be sorrows, which will receive their last bitterness only in
death. They are all too painful to be sustained, unless they have
been wisely foreseen. Let us think of misfortune, as of certain
characters, with whom our lot may one day compel us to consort.
It is novelty alone, which gives our emotions extreme keenness.
Whoever has strength of character, may learn to endure anything.
The red men of the American wilderness are most impressive
examples of this truth. Time, however, is the most efficacious
teacher of the lesson of endurance. Poussin, in his painting of
Eudomidas, has delineated the human heart with fidelity. The young
girl of the piece abandons herself to despair. Half stretched upon the
earth, her head falls supinely on the knees of the aged mother of
the dying. This mother is sitting. Her attitude announces mingled
meditation and grief. Amidst her tears, we trace firmness on her
visage. One of the two women is taking her first lesson of misery.
The other has already passed through a long apprenticeship of grief.
[13]
Reflection imparts anticipated experience. It takes from misery
that air of novelty, which renders it terrible. When a wise man
experiences a reverse, his new position has been foreseen. He has
measured the sorrows, and prepared the consolations. Into
whatever scene of trial he is brought, he will show in no one the
embarrassment of a stranger.
Taught to be conscious that we are feeble combatants, thrown
upon an arena of strife, let us not calculate that destiny has no
blows in store for us. Let us prepare for wounds, painful and slow to
heal. Let us blunt the darts of misfortune in advance. Then, if they
strike they will not penetrate so deep. But in premeditating the trials,
which may be in reserve for our courage, let not anticipated
solicitude disturb the present. Of all mental efforts, foresight is the
most difficult to regulate. If we have it not, we fall into reverses
unprepared. If we exercise it too far, we are perpetually miserable by
anticipation.
The philosopher prepares himself for contingent perils by
processes which impart a keener pleasure to present enjoyment. He
better understands the value of the moments of joy, and learns to
dispel the fears, which might mar their tranquillity. That is a gloomy
wisdom, which condemns the precepts that invite us to draw, from
the uncertainty of our lot, a motive to embellish the moment of
actual happiness. Transient beings, around whom everything is
changing and in motion, adopt my maxims. Let us aid those who
surround us, to put them in practice. Let us render those who are
happy today more happy. Tomorrow the opportunity may have
passed forever.
As though nature had not sowed sufficient sorrows in our path
during our short career, we have added to the mass by our own
invention. The offspring of our vanity and puerile prejudices, these
factitious pains seem sometimes more difficult to support, than real
evils. A warrior, who has shown fearless courage in the deadly
breach, has passed a sleepless night, because he was not invited to
a party, or a feast; or because a riband, or a diploma has not been
added to the many, with which he is already decorated. I had been
informed, that the wife and son of a distinguished acquaintance
were dangerously sick. I met him pale, and thoughtful. I was
meditating, how to give him hope in regard to the objects of his
supposed anxiety. While I was hesitating how to address him, he
made known the subject of his real inquietude. He was in
expectation of a high employment. The man of power, in whose
hand was the gift, had just received him coldly a second time. He
was anxiously calculating his remaining chances, and striving to
divine the causes of his discouraging reception.
To avoid such ridiculous agonies, let us adopt a maxim, not the
less true, because the phrase, in which I express it, may seem
trivial. Three quarters and half the remaining quarter of our
vexations are not worth wasting a thought upon their cause. I add,
that even in expectations which appear important, we ought to fear
trusting too little to chance. The order of events, which we call by
this name, is often more sage than any that human calculation can
arrange. If it decides in a manner which at first view seems greatly
against us, let us defer our accusations, until we have more
thoroughly tested the event. I have met a man, who had long been
an aspirant for a certain place, with a radiant countenance, having
just obtained it. Three months afterwards, he would have purchased
at any price the power of recalling events. I have seen another
friend in desolation, because he could not obtain the hand of the
daughter of a man, whose enterprises promised an immense
fortune. He had been rejected. The speculations of her father all
failed; and the reputation of his integrity and good faith with them.
The despairing lover would have shared the poverty and disgrace of
a helpless family; and would have been tormented, besides, with an
incompatible union, of itself sufficient to have rendered him
miserable in the midst of all the expected prosperity. One event is
contemplated with a charmed eye; another with despair. The issue
alone can declare, which of the two we ought to have desired.
I grant, that we are surrounded by real dangers. I pretend not to
be above suffering; and I attach no merit to becoming the reckless
dupe of men or chance. The highest philosophy is at the same time
the most simple and practicable. There is no error more common
than one, which is taken for profound wisdom. Most men look too
deep for the springs of events, and the motives of action. In many
alternatives, we shall be most wise in giving the reins to chance.
When we are menaced by an evident peril, let us summon all our
energy, and courageously struggle to ward it off. If, after all, neither
wisdom can evade it, nor bravery vanquish it, let us see, how true
wisdom ordains us to sustain it.
How many are ignorant of the value of resignation, or confound it
with weakness! The courage of resignation is, perhaps, the most
high and rare of all the forms of that virtue. Man received the gift
directly from the Author of his being. His desires, inquietudes,
misguided opinions, the fruits of an ambitious and incongruous
education, have weakened its force in the soul. Who can read the
anecdote of the American wilderness without thrilling emotion? An
Indian, descending the Niagara river, was drawn into the rapids
above the sublime cataract. The nursling of the desert rowed with
incredible vigor at first, in an intense struggle for life. Seeing his
efforts useless, he dropped his oars, sung his death song, and
floated in calmness down the abyss. His example is worthy of
imitation. While there is hope, let us nerve all our force, to avail
ourselves of all the chances it suggests. When hope ceases, and the
peril must be braved, wisdom counsels calm resignation.[14]
In regard to unconquerable evils, the true doctrine is not vain
resistance, but profound submission. It conceals the outline of what
we have to suffer, as with a veil. It hastens to bring us the fruit of
consoling time. It opens our eyes to a clearer view of the
possessions which remain to us. It precedes hope, as twilight ushers
in the day.
It is by laying down certain well ascertained principles of conduct,
and re-examining them every day, that a new empire is given to
reason, and that we learn to select the most eligible point in all
situations in life. The Greek philosophers were, incontestably, the
men, who best understood the art of becoming happy. Their studies
led them to the unwearied contemplation of the true good, the
advantages of elevation of mind, the danger of the passions, and a
calm submission to inevitable ills. Such were the habitual subjects of
their meditations and discourses. They suffered less from the evils of
life, only because they cultivated habits of profound reflection.
Among the moderns, in pursuit of happiness, some study only to
multiply their physical enjoyments; and limited to gross sensations,
differ little from brutes, except in discoursing about what they eat.
Others, higher in the scale of thought, cultivate the pleasures of
literature and the fine arts. But disciplining but a single class of their
powers, with a view to distinguish themselves from the vulgar, they
are not always more happy. True philosophy is chiefly conversant
about that kind of acquisition, which preëminently constitutes the
rational man, forms his reason, and places him, as a master, in the
midst of an unreflecting world surrounded by children full of
ignorance and fatuity.
Effective Robotics Programming with ROS Third Edition Anil Mahtani Luis Sanchez Enrique Fernandez Aaron Martinez
L E T T E R V I I I .
O F I N D E P E N D E N C E .
We distinguish many kinds of liberty. That which we owe to equal
laws, without being indispensable to a philosopher, renders the
attainment of happiness more easy to him. However men differ in
their political opinions, they all have an instinctive desire to be free.
Every one is reluctant and afraid to submit himself to the capricious
power of those about him. The thirst of power is only another form
of this ardor for independence.
With what interest we read in history of those ignorant tribes,
unknown to fame, whose liberty and simple manners at once
astonish and delight us? When visiting the isles of Greece, where the
charm of memory rendered the view of their actual slavery more
revolting, what delight the traveller experiences in traversing the
little isle of Casos which had never submitted to the Ottoman yoke!
He there found the usages of the ancient Greeks, their costume,
their beauty and their amiable and elevated natural manner. This isle
is but a rock. But its dangerous shores have defended it against
tyranny. Associations with the songs of Homer and Hesiod are
renewed. Such a picture delights even a people whose manners are
refined to a degree tending to depravation. Thus those opulent
citizens who find the country a place of exile still decorate their
splendid halls with landscapes and flowers.
Let not a sensitive and wandering imagination kindle too readily at
the recitals of travellers. Were we to transport ourselves to one of
those remote points of the earth where felicity is represented to
have chosen her asylum, new usages, manners and pleasures, and a
foreign people every moment reminding us that we are strangers,
would, perhaps, give birth to the most painful regrets. When in our
youth we were charmed as we read of the prodigies of Athens and
Rome, we uttered the wish that we had been born in those
renowned republics. There is little doubt that, had our wish been
realized, we should be glad to escape their storms, in exchange for
obscurely tranquil days.
It is a distinguished folly which impels men far from their country
in search of happiness. The greater portion, deceived in their hopes
after having wandered amidst danger, die with regret and sorrow,
worn out with vexation resulting from the broken ties and
remembrances of home. Home is the last thought that comes over
the departing mind. ‘Et dulces moriens reminiscitur Argos.’ Ubi patria
ibi bene is an adage which contains as much wise observation as
elevated patriotism. Our country is our common mother. We ought to
love and sustain her more firmly in her misery than in her prosperity.
Whatever manners, opinions and talents we carry into another
country, we are still strangers there. The manners which we adopt
are new and irksome. The eye sees nothing to awaken dear and
embellished remembrances; and we find in the heart of no one the
reverberating chord of ancient friendship and sympathy. We always
regret the places where we knew the first pleasures and the first
pains, and saw the first enchanting visions of life; the cherished
spots where we learned to love and be loved. If, returning there,
drawn back by an invincible sentiment, after a long absence we see
it again, what sorrows await us! We find ourselves strangers in our
own country. We ask for our parents and friends who departed in
succession. The blows were struck at long intervals. We receive
them all in a moment. We return to shed tears only on the tombs of
our fathers![15]
Retreat and competence everywhere supply a wise man a degree
of independence. Even when the sport of oppression and injustice,
he yields to these evils as the caprices of destiny. He would be free
in the midst of Constantinople under the government of the Sultan.
Another kind of liberty is the portion of but a few in our own
country—the liberty of disposing of our whole time at our choice. To
those who understand not the value of time, this liberty bequeaths a
heavy bondage. But to those who have learned the secret of
happiness it is of inestimable value. The privilege of the favored
possessor of opulence is a high one. Neither the slave of business,
fashion, opinion or routine, it is in his power at awaking to say ‘this
day is all my own.’[15a]
But moralists exclaim, ‘you must pay your debt: you must render
yourselves useful to society.’ Let me not be understood to inculcate
the doctrine of indolence. Industry will have wings and power when
you unite it to freedom. But how many repeat the hackneyed cry of
‘the debt to society,’ who, in the choice of their profession, had never
a thought but of its honors and emoluments! This man whose
industry in the pursuit of his choice proves that his toil is his
pleasure, that man who is in earnest to serve every one whom he
can oblige and who might have shone, had he chosen it, in the
career of ambition, but who, modest, proud, studious and free, lives
happily in the bosom of retreat, has this man done nothing to acquit
his debt? Is his example useless to society?
If my condition deny me leisure and independence in regard to
the disposal of my time, without bestowing much concern upon the
choice of my profession, I should choose that most favorable to free
thoughts, to breathing the open air, and, as much as might be, in
view of a beautiful nature. I should consider it as a most important
element in my happiness that I should be chiefly conversant with
people of compatible characters. The profession of an advocate,
perpetually conversant with the follies, vices and crimes of society, is
one of the most trying, both to integrity and philosophy. That of the
physician, continually witnessing groans, tears and physical
suffering, however painful to sensibility, may become the source of
high reflected pleasure to a generous and humane heart. I would
avoid a function the disquieting responsibility of which would disturb
my sleep. Above all, I should dread one of high honor and
emolument, connected with proportionate uncertainty of tenure.
The balance of enjoyment being taken into view, I should prefer
an occupation of privacy. It would be more easy at once to obtain
and preserve. It would expose me less to envy and competition.
Exempt from the inquietudes inspired by severe labors, and the
ennui of important etiquette, I should at least find an absolute
independence, every evening, at the relinquishment of my daily
routine of occupation, and I should suffer no care for the morrow; I
would learn to enhance the charms of my condition by thinking of
the agitation, regrets and alarms of those who are still swept by the
whirlwinds of life. In this way I would imitate him who, to procure a
more delicious repose, placed his couch under a tent near the sea,
to be lulled by the dashing of its waves and the noise of its storms.
But it is time to contemplate the most useful kind of liberty, the only
indispensable kind, and happily one which is accessible to all. It is
the liberty resulting from self-command and inward mastery of
ourselves. It has a value to cause all others to be forgotten—a value
which no other kind can replace.
What liberty can that man enjoy who is the slave of ambition? A
gesture, a look of the eye, a smile affrightens him and causes him
painful and trembling calculations what that sinister sign of his
master may presage.
Look at the opulent merchant whose hopes are the sport of the
winds, seas, robbers, changes of trade, municipal regulations, and a
crowd of agents who seem subordinate, but who really command
him.
Whatever kind of liberty we aim to possess, we may certainly
conclude that the surest means to enjoy it is to have few wants. But
how restrain our wants? The greater portion are happily placed by
their condition where they are ignorant of the objects which most
powerfully excite and seduce desire. The golden mean secludes
them from many temptations full of the bitterest regret, and exacts
of them little effort of wisdom. In the class of men of leisure and
elevated mind there are two means of rising above many wants.
The more austere philosophers have altogether disdained those
pleasures which they could never hope to obtain. Reducing
themselves to the limits of the strictest necessity, they indemnify
themselves for some privations by the certainty of being secured
from many pains, and by the sentiment of conscious independence.
This is, doubtless, one of the surest means of obtaining
independence; and they who attempt to employ any other, differ
from the vulgar by their principles rather than their conduct.
How many objects, of which the contemplation awakens the
desires, would have nothing dangerous if we could always exercise a
stern self-control over our minds! The surest means of exercising
this self-control is to reduce the number of our wants. To do it, I
admit, demands a rare elevation of mind and the exercise of a high
degree of philosophy. But since its value is beyond its cost, let us
dare to acquire it.
While the fleeting dreams of pleasure hover around us, let reason
still say to us, ‘an instant may dissipate them.’ Let us, then, be ready
to find a new pleasure in the consciousness of our firmness and our
masculine and vigorous independence. An enlightened mind reigns
over pleasures; and while they glitter around, enjoys all that are
innocent; but disdains a sigh or a regret when they have taken
wings and disappeared.
I commend the example of Alcibiades, the disciple of the graces
and of wisdom, who astonished in turn the proud Persian by his
dignity, and the Lacedemonian by his austerity. His enemies may
charge him with incessant change of principle. To me he seems
always the same, always superior to the men and circumstances that
surround him. Such strong mental stamina resemble those robust
plants that sustain, without annoyance, the extremes of heat and
cold.
Effective Robotics Programming with ROS Third Edition Anil Mahtani Luis Sanchez Enrique Fernandez Aaron Martinez
L E T T E R I X .
O F H E A L T H .
Health results from moderation, gayety and the absence of care.
Eternal wisdom has ordained, that the emotions which disturb our
days, are those which have a natural tendency to shorten them.[16]
If there were ground for a single charge against the justice of
nature, it would be, that the errors of inexperience seem punished
with too great severity. We prodigally waste the material of life and
enjoyment, as we do our other possessions, as if we thought it
inexhaustible.
To the errors of youth succeed the vices of mature age. Ambition
and cupidity, envy and hatred concur to devour the very aliment of
life. The storms which prostrate the moral faculties, equally sap the
physical energy. Every debasing passion is a consuming poison. To
what other source of evil can we assign those inquietudes and
puerile anxieties, which disturb the days of the greater portion of
mankind? They are occupied by trifling interests, and agitated by
vain debates. They watch for futile excitements, and are in
desolation from chimerical troubles. Pleasant emotions sustain life,
and produce upon it the effect of a gentle current of air upon flame.
Trains of thought habitually elevated, and sometimes inclined to
revery, impart pure and true gayety to the soul. To be able to
command this train is one of the rarest felicities of endowment. A
distinguished physician recorded in his tablets the apparent paradox,
that three quarters of men die of vexation or grief.
Huffland has published a work, upon the art of prolonging life, full
of interesting observations. ‘Philosophers,’ says he, ‘enjoy a delightful
leisure. Their thoughts, generally estranged from vulgar interests,
have nothing in common with those afflicting ideas, with which other
men are continually agitated and corroded. Their reflections are
agreeable by their variety, their vague liberty, and sometimes even
by their frivolity. Devoted to the pursuits of their choice, the
occupations of their taste, they dispose freely of their time.
Oftentimes they surround themselves with young people, that their
natural vivacity may be communicated to them, and, in some sort,
produce a renewal of their youth.’ We may make a distinction
between the different kinds of philosophy, in relation to their
influence upon the duration of life. Those which direct the mind
towards sublime contemplations, even were they in some degree
superstitious, such as those of Pythagoras and Plato, are the most
salutary. Next to them, I place those, the study of which, embracing
nature, gives enlarged and elevated ideas upon infinity, the stars,
the wonders of the universe, the heroic virtues, and other similar
subjects. Such were those of Democritus, Philolaus, Xenophanes, the
Stoics, and the ancient astronomers.’
‘I may cite next those less profound thinkers, who instead of
exacting difficult researches, seemed destined only to amuse the
mind; the followers of which philosophy, deviating wide from vulgar
opinion, peaceably sustain the arguments for and against the
propositions advanced. Such was the philosophy of Carneades and
the Academicians, to whom we may add the Grammarians and
Rhetoricians.’
‘But those which turn only upon painful subtilties, which are
affirmative, dogmatic and positive, which bend all facts and opinions
to form and adjust them to certain preconceived principles and
invariable measures; in fine, such as are thorny, arid, narrow and
contentious, these are fatal in tendency, and cannot but abridge the
life of those, who cultivate them. Of this class was the philosophy of
the Peripatetics, and that also of the Scholastics.’
Tumultuous passions and corroding cares are two sources of evil
influences, which philosophy avoids. Another influence, adverse to
life, is that mental feebleness, which renders persons perpetually
solicitous about their health, effeminate and unhappy. Fixing their
thoughts intensely on the functions of life, those functions, that are
subjects of this anxious inspection, labor. Imagining themselves sick,
they soon become so. The undoubting confidence that we shall not
be sick, is perhaps the best prophylactic for preserving health.
I am ignorant of the exact influence of moral upon physical action,
in relation to health. But of this I am confident, that it is prodigious;
that physicians have not made it a sufficient element in their
calculations, or employed it as they should; and that in future, under
a wise and more philosophic direction, it may operate an immense
result, both in restoring and preserving health.
A man reads a letter, which announces misfortunes, or sinister
events. His head turns. His appetite ceases. He becomes faint, and
oppressed; and his life is in danger. No contagion, however, no
physical blow has touched him. A thought has palsied his forces in a
moment; and has successively deranged every spring of life. We
have read of persons of feeble and uninformed mind, who have
fallen sick, in consequence of the cruel sport of those, who have
ingeniously alarmed their imagination, and cautiously indicated to
them a train of fatal symptoms. Since imagination can thus certainly
overturn our physical powers, why may it not, under certain
regulations, restore them? Among the numberless recorded cases of
cures, reputed miraculous, it is probable, that a great part may be
accounted for on this principle.[17]
Suppose a paralytic disciple of the school of miracles, whose head
is exalted with ideas of the mystic power of certain holy men, and
who is meditating on the succor which he expects from a divine
interposition manifested in his favor. In an ecstasy of faith, he sees a
minister of heaven descend enveloped in light, who bids him ‘arise,
and walk.’ In a moment the unknown nervous energy, excited by the
mysterious power of faith, touches the countless inert and relaxed
movements. The man arises and walks. During the siege of Lyons,
when bombs fell on the hospital, the terrified paralytics arose and
fled.
I am not disposed to question all the cures, which in France have
been attributed to magnetism. We know, what a salutary effect the
sight of his physician produces on the patient, who has confidence in
him. His cheerful and encouraging conversations are among the
most efficient remedies. If we entertained a long cherished and
intimate persuasion, that by certain signs, or touches, he could
dispel our complaints, his gestures would have a high moral and
physical influence. Magnetism was in this sense, as Bailly justly
remarked, a true experiment upon the power of the imagination. At
the moment of its greatest sway, while some regarded it an infallible
specific, and others deemed it entirely inefficient, another class held
it in just estimation. I cite an extract from the report of the Academy
of Science.
‘We have sought,’ say they, ‘to recognise the presence of the
magnetic fluid. But it escaped our senses. It was said, that its action
upon animated bodies was the sole proof of its existence. The
experiments, which we made upon ourselves, convinced us, that, as
soon as we diverted our attention, it was powerless. Trials made
upon the sick taught us, that infancy, which is unsusceptible of
prejudice experienced nothing from it; that mental alienation
resisted the action of magnetism, even in an habitual condition of
excitability of the nerves, where the action ought to have been most
sensible. The effects which are attributed to this fluid, are not
visible, except when the imagination is forewarned, and capable of
being struck. Imagination, then, seems to be the principle of the
action.
‘It remained to be seen, whether we could reproduce these effects
by the influence of imagination alone. We attempted it, and fully
succeeded. Without touching the subjects, who believed themselves
magnetised, and without employing any sign, they complained of
pain and a great sensation of heat. On subjects, endowed with more
excitable nerves, we produced convulsions, and what they called
crises. We have seen an exalted imagination become sufficiently
energetic to take away the power of speech in a moment. At the
same time, we proved the nullity of magnetism, put in opposition
with the imagination. Magnetism alone, employed for thirty minutes,
produced no effect. Imagination put in action produced upon the
same person, with the same means, in circumstances absolutely
similar, a strong, and well defined convulsion.
‘In fine, to complete the demonstration, and to finish the painting
of the effect of the imagination, a power equally capable of
agitating, and calming, we have caused those convulsions to cease
by the same power, which produced them—the power of the
imagination.
‘What we have learned, or, at least what has been confirmed to us
in a demonstrative and evident manner, by examination of the
processes of magnetism is, that man can act upon man at every
moment and almost at will, by striking his imagination; that signs
and gestures the most simple may have effects the most powerful;
and that the influence which may be exerted upon the imagination,
may be reduced to an art, and conducted by method.’
These truths had never before acquired so much evidence. We
know, that cures may be wrought by the single influence of
imagination. Ambrose Paré Boerhaave, and many other physicians,
have cited striking proofs of this fact. The first of these writers
procured abundant sweats for a patient, in making him believe that
a perfectly inert substance given him, was a violent sudorific.
It is worthy of the attention of moralists and physiologists, as well
as physicians, to examine, to what point we may obtain salutary
effects, by exciting the imagination. But perhaps, there would soon
be cause to dread the perilous influence of this art, which can kill, as
well as make alive. This excitable and vivid faculty is never more
easily put in operation, that when acted upon by the presentiments
of charlatanism and superstition.
We possess another means of operation, which may be exercised
without danger, and the power of which is, also, capable of
producing prodigies. Education rendering most men feeble and
timid, they are ignorant, how much an energetic will can accomplish.
It is able to shield us from many maladies; and to hasten the cure of
those under which we labor.
In mortal epidemics, the physicians, who are alarmed at their
danger, are ordinarily the first victims. Fear plunges the system into
that state of debility, which predisposes it to fatal impressions, while
the moral force of confidence, communicating its aid to physical
energy, enables it to repel contagion.
I could cite many distinguished names of men, who attributed
their cure, in desperate maladies, to the courage which never
forsook them, and to the efforts which they made to keep alive the
vital spark, when ready to become extinct. One of them pleasantly
said, ‘I should have died like the rest, had I wished it.’[18]
Pecklin, Barthes and others think that extreme desire to see a
beloved person once more, has sometimes a power to retard death.
It is a delightful idea. I feel with what intense ardor one might desire
to live another day, another hour, to see a friend or a child for the
last time. The flame of love, replacing that of life, blazes up for a
moment before both are quenched in the final darkness. The last
prayer is accorded; and life terminates in tasting that pleasure for
which it was prolonged. If this be true, the principle on which the
most touching incident of romance is founded, is not a fiction.
I have no need to say that an energetic will to recover from
sickness has no point of analogy with that fearful solicitude which
the greater part of the sick experience. The latter, produced by
mental feebleness, increases the inquietude and aggravates the
danger. Even indifference would be preferable. If education had
imparted to us the advantages of an energetic will and real force of
mind, if from infancy we had been convinced of the efficacy of this
moral power, we have no means to determine that it would not have
been, in union with the desire of life, an element in the means of
healing our maladies.
Medicine is still a science so conjectural that the most salutary
method of cure, in my view, is that which strives not to contradict
nature, but to second her efforts by moral means. I am ready to
believe that amidst the real or imagined triumphs of science, those
of medicine will, in the centuries to come, hold a rank to which its
past achievements will have borne no proportion. But what an
immense amount of experiment will be necessary! How many
unfortunate beings must contribute to the expense of these
experiments!
Contrary to the general opinion, I highly esteem physicians and
think but very little of medicine. In the profession of medicine we
find the greatest number of men of solid minds and various
erudition; and the best friends of humanity. But they are in the habit
of vaunting the progress of their science. To me it seems incessantly
changing its principles, without ever varying its results. The systems
of various great men have been successively received and rejected.
Do we, however, imagine that the great physicians who have
preceded us were more unfortunate in their practice than those of
our days? Among the most eminent physicians of our cities, one
practises by administering strong cathartics. Another is resolute for
copious bleeding. A third bids us watch and wait the indications of
nature. Each of these assumes that the system of the rest is fatal—
and so, it would seem, it should be. At the end of the year, however,
I doubt if any one of them all has more reproaches to make, as
regards want of success, than any other.
From these facts, there are those who hold that it is most prudent
to confide to nature, as the physician; forgetful that, if he could
bring no other remedy than hope, he unites moral to physical aid.
Yet, the very persons who, in health are readiest to maintain this
doctrine, like children who are heroes during the day but cowards in
the dark, when they are sick, are as prompt as others in sending for
the physician.
Even if agitation and fear had not fatal effects, in rendering us
more accessible to maladies, wisdom would strive to banish them, in
pursuit of the science of happiness. Fear, by anticipating agony,
doubles our sufferings. If there could exist a rational ground for
continual inquietude, it would be found in a frail constitution. But
how many men of the feeblest health survive those of the most
vigorous and robust frame! Calculations upon the duration of life are
so uncertain that we can always make them in our favor.
To him who cultivates a mild and pleasant philosophy, old age
itself should not be contemplated with alarm. It may seem a paradox
to say that all men are nearly of the same age, in reference to their
chances of another day. Men are as confident of seeing tomorrow
and the succeeding day, at eighty, as at sixteen. Such is the beautiful
veil with which nature conceals from us the darkness of the future.
In general, men have less sympathy for the suffering than their
condition ought to inspire. We meet them with a sad face and are
more earnest to show them that we are afflicted ourselves, than to
seek to cheer their dejection. We multiply so many questions
touching their health that it would seem as if we feared to allow
them to forget that they were sick.
Of all subjects of conversation, my own pains and physical
infirmities have become the least interesting to me; as I know they
must be to others. I do not wish that those who surround my sick
bed should converse as though arranging the preparations for my
last dress, or determining the hour of my interment.
If we would live in peace, and die in tranquillity, let us, as much as
possible, avoid importunate cares. Our business is to unite as many
friends as we may; and to beguile pain and sorrow by treasuring as
many resources of innocent amusement as our means will admit. If
our sufferings become painful and incurable, we must concentrate
our mental energy and settle on our solitary powers of endurance.
We die, or we recover. Nature, though calm, moves irresistibly to her
point; and complaint is always worse than useless.[19]
But in arming ourselves with courage to support our own evils, let
us preserve sensibility and sympathy for the sufferings of others. It
is among the dangerously sick that we find those unfortunate beings
who are most worthy to inspire our pity. Their only expectation is
death, preceded by cruel tortures; and yet they, probably, suffer less
for themselves than for weeping dependents whom they are leaving,
it may be, without a single prop. Ah! during the few days of sorrow
that remain to them on the earth, how earnestly ought we to strive
to mitigate their pains, to calm their alarms and animate their feeble
hopes! Blessed be that beneficent being who shall call one smile
more upon their dying lips![20]
Effective Robotics Programming with ROS Third Edition Anil Mahtani Luis Sanchez Enrique Fernandez Aaron Martinez
L E T T E R X .
O F C O M P E T E N C E .
Pretended sages announce to us, with sententious gravity, that
virtue ought to be the single object of our desires; that,
strengthened by it, we can support privations and misery without
suffering. Useless moralists! Shall I yield faith to precepts which the
experience of every day falsifies? It is only necessary, in refutation,
to present a man who has broken his limb, or whose children suffer
hunger.
His plan is wise, who examines, with a judgment free from
ambition, the amount of fortune necessary to competence in his
case, viewed in all its bearings; and commences the steady pursuit
of it. Having reached that measure, if his desires impel him beyond
the limit which, in a more reasonable hour, he prescribed for himself,
he henceforward strives to be happy by sacrificing enjoyment. He
barters it for a very uncertain means of purchasing even pleasures.
In this way competence becomes useless to the greater part of
those who obtain it. Victims of the common folly, and still wishing a
little more, they lose, in the effort to get rich, the time which they
ought to spend in enjoyment. We see grasping and adroit
speculators on every side; and, but rarely, men who know how to
employ the resources of a moderate fortune. It is not the art of
acquiring beyond competence, but of wisely spending, that we need
to learn.
Our business in life is to be happy; and yet, simple and obvious as
this truism is, the greater number disdain or forget it. To judge from
the passions and objects that we see exciting man to action, we
should suppose that he was placed on the earth, not to become
happy, but rich.
To what purpose so many cares and studies? ‘That man,’ we are
answered with a peculiar emphasis, ‘has an immense income.’ In his
rare, brilliant and envied condition, if he does not vegetate under the
weight of ennui, I recognise in him a man of astonishing merit.
The opulent may be divided into two classes. The employment of
the one is to watch over their expenditures. The other study the
mode of dissipating their revenue. Can I present, in detail, the cares
and vexations which an immense fortune brings? The possessor
leaves discussion with his tenants, to commence angry disputes with
his workmen. From these he departs to listen to the schemes of
projectors, or to the information of advocates. Is not such a result
dearly purchased at the expense of repose, independence and time?
Would it not be better to relinquish a part of these possessions, in
order to dispose, in peace, of the remainder? I admit that a man
who devotes himself to lucrative pursuits is not overwhelmed with
continual ennui. The banker respires again, after having grown pale
over his accounts. A speculation has succeeded, and the
enchantment of success banishes his alarms, fatigues and slavery.
But he whose purpose in life is to secure as many happy moments
as he can, and who sees how many innocent pleasures the other
allows to escape him, would refuse his fortune at the price which he
pays for it.
Another opulent class inherit fortunes acquired by the industry and
sacrifices of their fathers. Rendered effeminate in a school, the
reverse of that in which their fathers were trained, without resources
in themselves, accustomed from infancy to have their least desires
anticipated, under the influence of feeble parents, pliant and servile
instructers, greedy servants and a seducing world, their appetite is
early palled, and every pleasure in life worn out.
But suppose the rich heir brought up as though he were not rich,
destiny places before him a strange alternative. If he succeed in
resisting desires which everything excites and favors, what painful
struggles! If he yield to them, what effort can preserve him an
untainted mind? The experience of all time declares the
improbability that he will resist. So many pretended friends are at
hand to take up the cause of the present against the future, a cause,

More Related Content

PDF
Effective Robotics Programming with ROS Anil Mahtani
PDF
ROS_Course_Syllabus learning path for operating system
PDF
Lentin joseph learning robotics using python design, simulate, program, an...
PPTX
Ros Kd
PDF
ROS and Unity.pdf
PDF
ROS Workshop Proposal
PDF
ROS2-Developers-Guide-hands on experience.pdf
Effective Robotics Programming with ROS Anil Mahtani
ROS_Course_Syllabus learning path for operating system
Lentin joseph learning robotics using python design, simulate, program, an...
Ros Kd
ROS and Unity.pdf
ROS Workshop Proposal
ROS2-Developers-Guide-hands on experience.pdf

Similar to Effective Robotics Programming with ROS Third Edition Anil Mahtani Luis Sanchez Enrique Fernandez Aaron Martinez (20)

PDF
ROS - An open source platform for robotics software developers (lecture).pdf
PDF
Building Robotics Application at Scale using OpenSource from Zero to Hero
PPTX
ROS Based Programming and Visualization of Quadrotor Helicopters
PPTX
rosnotes_1djsjsmsmmsmsndndndndndndnndndnjdjd
PPTX
10. ROS (1).pptx
PDF
nd209_Robo_syllabus_v2.pdf
PDF
Building Your Robot using AWS Robomaker
PDF
HuongdanlaptrinhECE5463_ROSTutorialLecture3
PDF
Let's build a robot with ROS - Internet of Things, Hardware & Robotics meetup...
PDF
Copy of BITS Robocon Orientation 2022.pdf
PDF
Robotics_L7 - ROS_for_beginner_for _all.pdf
PDF
Robotics and ROS
PDF
Simulating TUM Drone 2.0 by ROS
PDF
IR - Lect 1 - Pre-Cursor - 27.07.2021.pdf
PDF
My ROS Experience
PDF
A real use case of ROS
PDF
B.Tech 5th Semester Industrial Robotics Notes Module- VI
PDF
Raspberry Pi + ROS
PDF
Robot Control using ROS: an Introduction
PDF
Ros rov talk
ROS - An open source platform for robotics software developers (lecture).pdf
Building Robotics Application at Scale using OpenSource from Zero to Hero
ROS Based Programming and Visualization of Quadrotor Helicopters
rosnotes_1djsjsmsmmsmsndndndndndndnndndnjdjd
10. ROS (1).pptx
nd209_Robo_syllabus_v2.pdf
Building Your Robot using AWS Robomaker
HuongdanlaptrinhECE5463_ROSTutorialLecture3
Let's build a robot with ROS - Internet of Things, Hardware & Robotics meetup...
Copy of BITS Robocon Orientation 2022.pdf
Robotics_L7 - ROS_for_beginner_for _all.pdf
Robotics and ROS
Simulating TUM Drone 2.0 by ROS
IR - Lect 1 - Pre-Cursor - 27.07.2021.pdf
My ROS Experience
A real use case of ROS
B.Tech 5th Semester Industrial Robotics Notes Module- VI
Raspberry Pi + ROS
Robot Control using ROS: an Introduction
Ros rov talk
Ad

Recently uploaded (20)

PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
Open Quiz Monsoon Mind Game Final Set.pptx
PDF
Basic Mud Logging Guide for educational purpose
PDF
The Final Stretch: How to Release a Game and Not Die in the Process.
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PPTX
COMPUTERS AS DATA ANALYSIS IN PRECLINICAL DEVELOPMENT.pptx
PDF
Pre independence Education in Inndia.pdf
PDF
BÀI TẬP TEST BỔ TRỢ THEO TỪNG CHỦ ĐỀ CỦA TỪNG UNIT KÈM BÀI TẬP NGHE - TIẾNG A...
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPTX
Cell Structure & Organelles in detailed.
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
Cardiovascular Pharmacology for pharmacy students.pptx
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
STATICS OF THE RIGID BODIES Hibbelers.pdf
Open Quiz Monsoon Mind Game Final Set.pptx
Basic Mud Logging Guide for educational purpose
The Final Stretch: How to Release a Game and Not Die in the Process.
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
COMPUTERS AS DATA ANALYSIS IN PRECLINICAL DEVELOPMENT.pptx
Pre independence Education in Inndia.pdf
BÀI TẬP TEST BỔ TRỢ THEO TỪNG CHỦ ĐỀ CỦA TỪNG UNIT KÈM BÀI TẬP NGHE - TIẾNG A...
102 student loan defaulters named and shamed – Is someone you know on the list?
TR - Agricultural Crops Production NC III.pdf
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Cell Structure & Organelles in detailed.
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Cardiovascular Pharmacology for pharmacy students.pptx
Abdominal Access Techniques with Prof. Dr. R K Mishra
Microbial disease of the cardiovascular and lymphatic systems
PPH.pptx obstetrics and gynecology in nursing
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Ad

Effective Robotics Programming with ROS Third Edition Anil Mahtani Luis Sanchez Enrique Fernandez Aaron Martinez

  • 1. Effective Robotics Programming with ROS Third Edition Anil Mahtani Luis Sanchez Enrique Fernandez Aaron Martinez install download https://ebookmeta.com/product/effective-robotics-programming- with-ros-third-edition-anil-mahtani-luis-sanchez-enrique- fernandez-aaron-martinez/ Download more ebook from https://ebookmeta.com
  • 2. We believe these products will be a great fit for you. Click the link to download now, or visit ebookmeta.com to discover even more! Learning ROS for Robotics Programming Second Edition Enrique Fernandez Luis Sanchez Crespo Anil Mahtani Aaron Martinez https://ebookmeta.com/product/learning-ros-for-robotics- programming-second-edition-enrique-fernandez-luis-sanchez-crespo- anil-mahtani-aaron-martinez/ Robot Operating System (ROS) for Absolute Beginners: Robotics Programming Made Easy Lentin Joseph https://ebookmeta.com/product/robot-operating-system-ros-for- absolute-beginners-robotics-programming-made-easy-lentin-joseph/ Robot Operating System (ROS) for Absolute Beginners: Robotics Programming Made Easy 2nd Edition Lentin Joseph https://ebookmeta.com/product/robot-operating-system-ros-for- absolute-beginners-robotics-programming-made-easy-2nd-edition- lentin-joseph/ Bluebonnets and Bikers Wild Blooms Book 7 First Edition D Lilac Wild Blooms https://ebookmeta.com/product/bluebonnets-and-bikers-wild-blooms- book-7-first-edition-d-lilac-wild-blooms/
  • 3. Monkey with a Tool Belt and the Silly School Mystery Chris Monroe https://ebookmeta.com/product/monkey-with-a-tool-belt-and-the- silly-school-mystery-chris-monroe/ Evidential Reasoning in Archaeology 1st Edition Robert Chapman https://ebookmeta.com/product/evidential-reasoning-in- archaeology-1st-edition-robert-chapman/ Instant Pot Soups Nourishing Recipes for Every Season Alexis Mersel https://ebookmeta.com/product/instant-pot-soups-nourishing- recipes-for-every-season-alexis-mersel-2/ Russian Central Asia 1867 1917 A Study in Colonial Rule Richard A. Pierce https://ebookmeta.com/product/russian-central- asia-1867-1917-a-study-in-colonial-rule-richard-a-pierce/ The Norton Anthology of American Literature Volume 2 Robert S. Levine https://ebookmeta.com/product/the-norton-anthology-of-american- literature-volume-2-robert-s-levine/
  • 4. Ironmaking and Steelmaking Zushu Li Claire Davis https://ebookmeta.com/product/ironmaking-and-steelmaking-zushu- li-claire-davis/
  • 6. Table of Contents Effective Robotics Programming with ROS Third Edition Credits About the Authors About the Reviewer www.PacktPub.com eBooks, discount offers, and more Why subscribe? Customer Feedback Preface What this book covers What you need for this book Who this book is for Conventions Reader feedback Customer support Downloading the example code Downloading the color images of this book Errata Piracy Questions 1. Getting Started with ROS PC installation Installing ROS Kinetic using repositories Configuring your Ubuntu repositories Setting up your source.list file Setting up your keys Installing ROS Initializing rosdep Setting up the environment Getting rosinstall How to install VirtualBox and Ubuntu Downloading VirtualBox
  • 7. Creating the virtual machine Using ROS from a Docker image Installing Docker Getting and using ROS Docker images and containers Installing ROS in BeagleBone Black Prerequisites Setting up the local machine and source.list file Setting up your keys Installing the ROS packages Initializing rosdep for ROS Setting up the environment in the BeagleBone Black Getting rosinstall for BeagleBone Black Basic ROS example on the BeagleBone Black Summary 2. ROS Architecture and Concepts Understanding the ROS Filesystem level The workspace Packages Metapackages Messages Services Understanding the ROS Computation Graph level Nodes and nodelets Topics Services Messages Bags The ROS master Parameter Server Understanding the ROS Community level Tutorials to practise with ROS Navigating through the ROS filesystem Creating our own workspace Creating an ROS package and metapackage Building an ROS package Playing with ROS nodes
  • 8. Learning how to interact with topics Learning how to use services Using Parameter Server Creating nodes Building the node Creating msg and srv files Using the new srv and msg files The launch file Dynamic parameters Summary 3. Visualization and Debugging Tools Debugging ROS nodes Using the GDB debugger with ROS nodes Attaching a node to GDB while launching ROS Profiling a node with valgrind while launching ROS Enabling core dumps for ROS nodes Logging messages Outputting logging messages Setting the debug message level Configuring the debugging level of a particular node Giving names to messages Conditional and filtered messages Showing messages once, throttling, and other combinations Using rqt_console and rqt_logger_level to modify the logging level on the fly Inspecting the system Inspecting the node's graph online with rqt_graph Setting dynamic parameters Dealing with the unexpected Visualizing nodes diagnostics Plotting scalar data Creating a time series plot with rqt_plot Image visualization Visualizing a single image 3D visualization Visualizing data in a 3D world using rqt_rviz
  • 9. The relationship between topics and frames Visualizing frame transformations Saving and playing back data What is a bag file? Recording data in a bag file with rosbag Playing back a bag file Inspecting all the topics and messages in a bag file Using the rqt_gui and rqt plugins Summary 4. 3D Modeling and Simulation A 3D model of our robot in ROS Creating our first URDF file Explaining the file format Watching the 3D model on rviz Loading meshes to our models Making our robot model movable Physical and collision properties Xacro – a better way to write our robot models Using constants Using math Using macros Moving the robot with code 3D modeling with SketchUp Simulation in ROS Using our URDF 3D model in Gazebo Adding sensors to Gazebo Loading and using a map in Gazebo Moving the robot in Gazebo Summary 5. The Navigation Stack – Robot Setups The navigation stack in ROS Creating transforms Creating a broadcaster Creating a listener Watching the transformation tree Publishing sensor information
  • 10. Creating the laser node Publishing odometry information How Gazebo creates the odometry Using Gazebo to create the odometry Creating our own odometry Creating a base controller Creating our base controller Creating a map with ROS Saving the map using map_server Loading the map using map_server Summary 6. The Navigation Stack – Beyond Setups Creating a package Creating a robot configuration Configuring the costmaps – global_costmap and local_costmap Configuring the common parameters Configuring the global costmap Configuring the local costmap Base local planner configuration Creating a launch file for the navigation stack Setting up rviz for the navigation stack The 2D pose estimate The 2D nav goal The static map The particle cloud The robot's footprint The local costmap The global costmap The global plan The local plan The planner plan The current goal Adaptive Monte Carlo Localization Modifying parameters with rqt_reconfigure Avoiding obstacles Sending goals
  • 11. Summary 7. Manipulation with MoveIt! The MoveIt! architecture Motion planning The planning scene World geometry monitor Kinematics Collision checking Integrating an arm in MoveIt! What's in the box? Generating a MoveIt! package with the Setup Assistant Integration into RViz Integration into Gazebo or a real robotic arm Simple motion planning Planning a single goal Planning a random target Planning a predefined group state Displaying the target motion Motion planning with collisions Adding objects to the planning scene Removing objects from the planning scene Motion planning with point clouds The pick and place task The planning scene The target object to grasp The support surface Perception Grasping The pickup action The place action The demo mode Simulation in Gazebo Summary 8. Using Sensors and Actuators with ROS Using a joystick or a gamepad How does joy_node send joystick movements?
  • 12. Using joystick data to move our robot model Using Arduino to add sensors and actuators Creating an example program to use Arduino Robot platform controlled by ROS and Arduino Connecting your robot motors to ROS using Arduino Connecting encoders to your robot Controlling the wheel velocity Using a low-cost IMU – 9 degrees of freedom Installing Razor IMU ROS library How does Razor send data in ROS? Creating an ROS node to use data from the 9DoF sensor in our robot Using robot localization to fuse sensor data in your robot Using the IMU – Xsens MTi How does Xsens send data in ROS? Using a GPS system How GPS sends messages Creating an example project to use GPS Using a laser rangefinder – Hokuyo URG-04lx Understanding how the laser sends data in ROS Accessing the laser data and modifying it Creating a launch file Using the Kinect sensor to view objects in 3D How does Kinect send data from the sensors, and how do we see it? Creating an example to use Kinect Using servomotors – Dynamixel How does Dynamixel send and receive commands for the movements? Creating an example to use the servomotor Summary 9. Computer Vision ROS camera drivers support FireWire IEEE1394 cameras USB cameras Making your own USB camera driver with OpenCV
  • 13. ROS images Publishing images with ImageTransport OpenCV in ROS Installing OpenCV 3.0 Using OpenCV in ROS Visualizing the camera input images with rqt_image_view Camera calibration How to calibrate a camera Stereo calibration The ROS image pipeline Image pipeline for stereo cameras ROS packages useful for Computer Vision tasks Visual odometry Using visual odometry with viso2 Camera pose calibration Running the viso2 online demo Performing visual odometry with viso2 with a stereo camera Performing visual odometry with an RGBD camera Installing fovis Using fovis with the Kinect RGBD camera Computing the homography of two images Summary 10. Point Clouds Understanding the Point Cloud Library Different point cloud types Algorithms in PCL The PCL interface for ROS My first PCL program Creating point clouds Loading and saving point clouds to the disk Visualizing point clouds Filtering and downsampling Registration and matching Partitioning point clouds Segmentation Summary
  • 14. Index
  • 16. Effective Robotics Programming with ROS Third Edition Copyright © 2016 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, and its dealers and distributors will be held liable for any damages caused or alleged to be 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. First published: September 2013 Second edition: August 2015 Third edition: December 2016 Production reference: 1231216 Published by Packt Publishing Ltd. Livery Place
  • 17. 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78646-365-4 www.packtpub.com
  • 18. Credits Authors Anil Mahtani Luis Sánchez Enrique Fernández Aaron Martinez Reviewer Lentin Joseph Commissioning Editor Kartikey Pandey Acquisition Editor Narsimha Pai Content Development Editor Abhishek Jadhav Technical Editor Gaurav Suri Copy Editors Safis Editing Dipti Mankame
  • 19. Project Coordinator Judie Jose Proofreader Safis Editing Indexer Pratik Shirodkar Graphics Kirk D'Penha Production Coordinator Shantanu N. Zagade Cover Work Shantanu N. Zagade
  • 20. About the Authors Anil Mahtani is a computer scientist who has dedicated an important part of his career to underwater robotics. He first started working in the field with his master thesis, where he developed a software architecture for a low-cost ROV. During the development of his thesis, he also became the team leader and lead developer of AVORA, a team of university students that designed and developed an autonomous underwater vehicle for the Students Autonomous Underwater Challenge – Europe (SAUC-E) in 2012. That same year, Anil Mahtani completed his thesis and his MSc in Computer Science at the University of Las Palmas de Gran Canaria and then became a Software Engineer at SeeByte Ltd, a world leader in smart software solutions for underwater systems. In 2015, he joined Dell Secureworks as a Software Engineer, where he applies his knowledge and skills toward developing intrusion detection and prevention systems. During his time at SeeByte Ltd, Anil Mahtani played a key role in the development of several semi-autonomous and autonomous underwater systems for the military and oil and gas industries. In those projects, he was heavily involved in the development of autonomy systems, the design of distributed software architectures, and low-level software development and also contributed in providing Computer Vision solutions for front-looking sonar imagery. At SeeByte Ltd, he also achieved the position of project manager, managing a team of engineers developing and maintaining the internal core C++ libraries. His professional interests lie mainly in software engineering, algorithms, data structures, distributed systems, networks, and operating systems. Anil's main role in robotics is to provide efficient and robust software solutions, addressing not only the current problems at hand but also foreseeing future problems or possible enhancements. Given his experience, he is also an asset when
  • 21. dealing with Computer Vision, machine learning, or control problems. Anil has also interests in DIY and electronics, and he has developed several Arduino libraries, which he has contributed back to the community. First of all, I would like to thank my family and friends for their support and for always being there when I needed them. I would also like to thank my girlfriend Alex for her support and patience, and for being a constant source of inspiration. Finally, I would like to thank my colleagues Ihor Bilyy and Dan Good, who have taught me a lot, both personally and professionally, during these new steps in my career as a software engineer. Luis Sánchez has completed his dual master's degree in electronics and telecommunication engineering at the University of Las Palmas de Gran Canaria. He has collaborated with different research groups as the Institute for Technological Development and Innovation (IDETIC), the Oceanic Platform of Canary Islands (PLOCAN), and the Institute of Applied Microelectronics (IUMA) where he actually researches on imaging super-resolution algorithms. His professional interests lie in Computer Vision, signal processing, and electronic design applied on robotics systems. For this reason, he joined the AVORA team, a group of young engineers and students working on the development of Underwater Autonomous Vehicles (AUV) from scratch. Inside this project, Luis has started developing acoustic and Computer Vision systems, extracting information from different sensors such as hydrophones, sonar, or camera. With a strong background gained in marine technology, Luis cofounded Subsea Mechatronics, a young start-up, where he works
  • 22. on developing remotely operated and autonomous vehicles for underwater environments. Here's what Dario Sosa Cabrera, a marine technologies engineer and entrepreneur (and the cofounder and maker of LPA Fabrika: Gran Canaria Maker Space) has to say about Luis: "He is very enthusiastic and an engineer in multiple disciplines. He is responsible for his work. He can manage himself and can take up responsibilities as a team leader, as demonstrated at the euRathlon competition. His background in electronics and telecommunications allows him to cover a wide range of expertise from signal processing and software, to electronic design and fabrication." Luis has participated as a technical reviewer of the previous version of Learning ROS for Robotics Programming and as a cowriter of the second edition. First, I have to acknowledge Aaron, Anil, and Enrique for inviting me to participate in this book. It has been a pleasure to return to work with them. Also, I want to thank the Subsea Mechatronics team for the great experience working with heavy underwater robots, we grew together during these years. I have to mention LPA Fabrika – Gran Canaria Maker Space for the enthusiasm preparing and teaching educational robotics and technological projects; sharing a workspace with kids can be really motivating. Finally, I will have to thank my family and my girlfriend for the big support and encouragement in every project where I'm involved. I want to dedicate my contribution in this book to them. Enrique Fernández has a PhD in computer engineering and an extensive background in robotics. His PhD thesis addressed the problem of Path Planning for Autonomous Underwater Gliders, but
  • 23. he also worked on other robotics projects, including SLAM, perception, vision, and control. During his doctorate, he joined the Center of Underwater Robotics Research in the University of Girona, where he developed Visual SLAM and INS modules in ROS for Autonomous Underwater Vehicles (AUVs), and participated in the Student Autonomous Underwater Challenge, Europe (SAUC-E) in 2012, and collaborated in the 2013 edition; in 2012, he was awarded a prize. During his PhD, Enrique published several conference papers and publications to top robotics conferences, such as the International Conference of Robotics and Automation (ICRA). He has also authored some book chapters and ROS books. Later, Enrique joined PAL Robotics as a SLAM engineer in June 2013. There he worked with the REEM and REEM-C humanoid robots using ROS software and also contributed to the open source community, mainly to ROS Control repository, being one of the maintainers nowadays. In 2015, he joined Clearpath Robotics to work on the Autonomy team, developing perception algorithms. He has worked on the software that runs on the industrial mobile robots OTTO 1500 and OTTO 100, which has been deployed into the facilities of multiple large industry companies, such as General Electric and John Deere. I would like to thank the coauthors of the book for their dedication. I also want to say thanks to the members of my research group in Las Palmas de Gran Canaria and the Center of Underwater Robotics Research in Girona. I learned a lot about robotics then, and I started to work with ROS. Thanks also to the ex-colleagues from PAL Robotics, who received me with open hands, and have given me the opportunity to learn even more from ROS and (humanoid) robots. Last by not least, to my current colleagues at Clearpath Robotics, where I have mastered ROS and contributed to the software that runs 24/7 in the self-
  • 24. driving robots we have sold for the Industry 4.0. Finally, thanks to my family and friends for their help and support, especially Eva. Aaron Martinez is a computer engineer, entrepreneur, and expert in digital fabrication. He did his master's thesis in 2010 at the IUCTC (Instituto Universitario de Ciencias y Tecnologias Ciberneticas) in the University of Las Palmas de Gran Canaria. He prepared his master's thesis in the field of telepresence using immersive devices and robotic platforms. After completing his academic career, he attended an internship program at The Institute for Robotics in the Johannes Kepler University in Linz, Austria. During his internship program, he worked as part of a development team of a mobile platform using ROS and the navigation stack. After that, he was involved in some projects related to robotics; one of them is the AVORA project in the University of Las Palmas de Gran Canaria. In this project, he worked on the creation of an AUV to participate in the Student Autonomous Underwater Challenge-Europe (SAUC-E) in Italy. In 2012, he was responsible for manufacturing this project; in 2013, he helped to adapt the navigation stack and other algorithms from ROS to the robotic platform. Recently, Aaron created his own company named SubSeaMechatronics, SL. This company works with projects related with underwater robotics and telecontrol systems. They are also designing and manufacturing subsea sensors. The company manufactures devices for other companies and research and development institutes. Aaron has experience in many fields, such as programming, robotics, mechatronics, and digital fabrication as well as many devices, such as Arduino, BeagleBone, Servers, and LIDAR, and nowadays he is designing in SubSeaMechatronics SL some robotics platforms for underwater and aerial environments.
  • 25. I would like to thank my girlfriend who has supported me while writing this book and gave me motivation to continue growing professionally. I also want to thank Donato Monopoli, Head of Biomedical Engineering Department at ITC (Canary-Islands Institute of Technology), and all the staff there. Thanks for teaching me all I know about digital fabrication, machinery, and engineering tissue. I spent the best years of my life in your workshop. Thanks to my colleagues in the university, especially Alexis Quesada, who gave me the opportunity to create my first robot in my master's thesis. I have learned a lot about robotics working with them. Finally, thanks to my family and friends for their help and support.
  • 26. About the Reviewer Lentin Joseph is an author, entrepreneur, electronics engineer, robotics enthusiast, machine vision expert, embedded programmer, and the founder and CEO of Qbotics Labs (http://www.qboticslabs.com) in India. He completed his bachelor's degree in electronics and communication engineering at the Federal Institute of Science and Technology (FISAT), Kerala. For his final year engineering project, he made a social robot that can interact with people (http://www.technolabsz.com/2012/07/social-robot-my-final- year.html). The project was a huge success and was mentioned in many forms of visual and print media. The main features of this robot were that it can communicate with people and reply intelligently and has some image processing capabilities, such as face, motion, and color detection. The entire project was implemented using the Python programming language. His interest in robotics, image processing, and Python started with that project. After his graduation, for 3 years he worked at a start-up company focusing on robotics and image processing. In the meantime, he learned famous robotic software platforms, such as Robot Operating System (ROS), V-REP, Actin (a robotic simulation tool), and image processing libraries, such as OpenCV, OpenNI, and PCL. He also knows about robot 3D designing and embedded programming on Arduino and Tiva Launchpad. After 3 years of work experience, he started a new company named Qbotics Labs, which mainly focuses on research to build up some great products in domains, such as robotics and machine vision. He maintains a personal website (http://www.lentinjoseph.com) and a technology blog named technolabsz (http://www.technolabsz.com). He publishes his works on his tech blog. He was also a speaker at PyCon2013, India, on the topic Learning Robotics using Python.
  • 27. Lentin is the author of the books Learning Robotics using Python (refer to http://learn-robotics.com to find out more) and Mastering ROS for Robotics Programming (refer to http://mastering-ros.com to find out more) by Packt Publishing. The first book was about building an autonomous mobile robot using ROS and OpenCV. This book was launched in ICRA 2015 and was featured in the ROS blog, Robohub, OpenCV, the Python website, and various other such forums. The second book is for mastering robot operating system; this was also launched ICRA 2016, and it is one of the best seller book in ROS. Lentin and his team was a winner of HRATC 2016 challenge conducted as a part of ICRA 2016, and he was Also a finalist in the ICRA 2015 challenge, HRATC (http://www.icra2016.org/conference/challenges/).
  • 28. www.PacktPub.com eBooks, discount offers, and more 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.PacktPub.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.PacktPub.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 eBooks. https://www.packtpub.com/mapt Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry- leading tools to help you plan your personal development and advance your career. Why subscribe? Fully searchable across every book published by Packt Copy and paste, print, and bookmark content
  • 29. On demand and accessible via a web browser
  • 30. Customer Feedback Thank you for purchasing this Packt book. We take our commitment to improving our content and products to meet your needs seriously —that's why your feedback is so valuable. Whatever your feelings about your purchase, please consider leaving a review on this book's Amazon page. Not only will this help us, more importantly it will also help others in the community to make an informed decision about the resources that they invest in to learn. You can also review for us on a regular basis by joining our reviewers' club. If you're interested in joining, or would like to learn more about the benefits we offer, please contact us: <customerreviews@packtpub.com>.
  • 31. Preface Effective Robotics Programming with ROS, Third Edition gives you a comprehensive review of ROS, the Robot Operating System framework, which is used nowadays by hundreds of research groups and companies in the robotics industry. More importantly, ROS is also the painless entry point to robotics for nonprofessionals and students. This book will guide you through the installation process of ROS, and soon enough, you will be playing with the basic tools and understanding the different elements of the framework. The content of the book can be followed without any special devices, and each chapter comes with a series of source code examples and tutorials that you can run on your own computer. This is the only thing you need to follow the book. However, we also show you how to work with hardware so that you can connect your algorithms with the real world. Special care has been taken in choosing devices that are affordable for amateur users, but at the same time, the most typical sensors or actuators in robotics research are covered. Finally, the potential of ROS is illustrated with the ability to work with whole robots in a real or simulated environment. You will learn how to create your own robot and integrate it with a simulation by using the Gazebo simulator. From here, you will have the chance to explore the different aspects of creating a robot, such as perceiving the world using computer vision or point cloud analysis, navigating through the environment using the powerful navigation stack, and even being able to control robotic arms to interact with your surroundings using the MoveIt! package. By the end of the book, it is our hope that you will have a thorough understanding of the endless possibilities that ROS gives you when developing robotic systems.
  • 32. What this book covers Chapter 1, Getting Started with ROS, shows the easiest way you must follow in order to have a working installation of ROS. You will see how to install ROS on different platforms, and you will use ROS Kinetic throughout the rest of the book. This chapter describes how to make an installation from Debian packages, compile the sources, and make installations in virtual machines, Docker, and ARM CPU. Chapter 2, ROS Architecture and Concepts, is concerned with the concepts and tools provided by the ROS framework. We will introduce you to nodes, topics, and services, and you will also learn how to use them. Through a series of examples, we will illustrate how to debug a node and visualize the messages published through a topic. Chapter 3, Visualization and Debugging Tools, goes a step further in order to show you powerful tools to debug your nodes and visualize the information that goes through the node's graph along with the topics. ROS provides a logging API that allows you to diagnose node problems easily. In fact, we will see some powerful graphical tools, such as rqt_console and rqt_graph, as well as visualization interfaces, such as rqt_plot and rviz. Finally, this chapter explains how to record and play back messages using rosbag and rqt_bag. Chapter 4, 3D Modeling and Simulation, constitutes one of the first steps in order to implement your own robot in ROS. It shows you how to model a robot from scratch and run it in simulation using the Gazebo simulator. You will simulate sensors, such as cameras and laser range sensors. This will later allow you to use the whole navigation stack provided by ROS and other tools. Chapter 5, The Navigation Stack – Robot Setups, is the first of two chapters concerned with the ROS navigation stack. This chapter describes how to configure your robot so that it can be used with
  • 33. the navigation stack. In the same way, the stack is explained, along with several examples. Chapter 6, The Navigation Stack – Beyond Setups, continues the discussion of the previous chapter by showing how we can effectively make our robot navigate autonomously. It will use the navigation stack intensively for that. This chapter shows the great potential of ROS using the Gazebo simulator and RViz to create a virtual environment in which we can build a map, localize our robot, and do path planning with obstacle avoidance. Chapter 7, Manipulation with MoveIt!, is a set of tools for mobile manipulation in ROS. This chapter contains the documentation that you need to install this package. The chapter also contains example demonstrations with robotic arms that use MoveIt! for manipulation tasks, such as grasping, picking and placing, or simple motion planning with inverse kinematics. Chapter 8, Using Sensors and Actuators with ROS, literally connects ROS with the real world. This chapter goes through a number of common sensors and actuators that are supported in ROS, such as range lasers, servo motors, cameras, RGB-D sensors, and GPS. Moreover, we explain how to use embedded systems with microcontrollers, similar to the widely known Arduino boards. Chapter 9, Computer Vision, shows the support for cameras and computer vision tasks in ROS. This chapter starts with drivers available for FireWire and USB cameras so that you can connect them to your computer and capture images. You will then be able to calibrate your camera using the ROS calibration tools. Later, you will be able to use the image pipeline, which is explained in detail. Then, you will see how to use several APIs for vision and integrate OpenCV. Finally, the installation and usage of a visual odometry software is described.
  • 34. Chapter 10, Point Clouds, shows how to use Point Cloud Library in your ROS nodes. This chapter starts with the basics utilities, such as read or write a PCL snippet and the conversions needed to publish or subscribe to these messages. Then, you will create a pipeline with different nodes to process 3D data, and you will downsample, filter, and search for features using PCL.
  • 35. What you need for this book This book was written with the intention that almost everybody can follow it and run the source code examples provided with it. Basically, you need a computer with a Linux distribution. Although any Linux distribution should be fine, it is recommended that you use a version of Ubuntu 16.04 LTS. Then, you will use ROS Kinetic, which is installed according to the instructions given in Chapter 1, Getting Started with ROS. As regards the hardware requirements of your computer, in general, any computer or laptop is enough. However, it is advisable to use a dedicated graphics card in order to run the Gazebo simulator. Also, it will be good to have a good number of peripherals so that you can connect several sensors and actuators, including cameras and Arduino boards. You will also need Git (the git-core Debian package) in order to clone the repository with the source code provided with this book. Similarly, you are expected to have a basic knowledge of the Bash command line, GNU/Linux tools, and some C/C++ programming skills.
  • 36. Who this book is for This book is targeted at all robotics developers, from amateurs to professionals. It covers all the aspects involved in a whole robotic system and shows how ROS helps with the task of making a robot really autonomous. Anyone who is learning robotics and has heard about ROS but has never tried it will benefit from this book. Also, ROS beginners will learn advanced concepts and tools of this framework. Indeed, even regular users may learn something new from some particular chapters. Certainly, only the first three chapters are intended for new users; so those who already use ROS can skip these ones and go directly to the rest.
  • 37. Conventions In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning. Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "The rosdep command-line tool must be installed and initialized before you can use ROS." A block of code is set as follows: #include <ros/ros.h> #include <dynamic_reconfigure/server.h> #include <chapter2_tutorials/chapter2Config.h> When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold: dynamic_reconfigure::Server<chapter2_tutorials::ch apter2Config>::CallbackType f; f = boost::bind(&callback, _1, _2); Any command-line input or output is written as follows: $ sudo apt-get install python-rosdep $ sudo rosdep init $ rosdep update New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "When it finishes, you can start your virtual machine by clicking on the Start button."
  • 38. Note Warnings or important notes appear in a box like this. Tip Tips and tricks appear like this.
  • 39. Reader feedback Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail <feedback@packtpub.com>, and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
  • 40. Customer support Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase. Downloading the example code You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e- mailed directly to you. You can also download these code files from https://github.com/rosbook/effective_robotics_programming_with_ro s. The same code files are also available at https://github.com/PacktPublishing/Effective-Robotics-Programming- with-ROS. Downloading the color images of this book We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/EffectiveRo boticsProgrammingwithROSThirdEdition_ColorImages.pdf. Errata Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be
  • 41. grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title. To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section. Piracy Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy. Please contact us at <copyright@packtpub.com> with a link to the suspected pirated material. We appreciate your help in protecting our authors and our ability to bring you valuable content. Questions If you have a problem with any aspect of this book, you can contact us at <questions@packtpub.com>, and we will do our best to address the problem.
  • 42. Chapter 1. Getting Started with ROS Welcome to the first chapter of this book, where you will learn how to install ROS, the new standard software framework in robotics. This book is an update on Learning ROS for Robotics Programming - Second Edition, based in ROS Hydro/Indigo. With ROS, you will learn how to program and control your robots the easy way, using tons of examples and source code that will show you how to use sensors and devices, or how to add new functionalities, such as autonomous navigation, visual perception, and others, to your robot. Thanks to the open source ethos and a community that is developing state-of- the-art algorithms and providing new functionalities, ROS is growing every day. This book will cover the following topics: Installing ROS Kinetic framework on a compatible version of Ubuntu The basic operation of ROS Debugging and visualizing data Programming your robot using this framework Connecting sensors, actuators, and devices to create your robot Creating a 3D model to use in the simulator Using the navigation stack to make your robot autonomous In this chapter, we are going to install a full version of ROS Kinetic in Ubuntu. ROS is fully supported and recommended for Ubuntu, and it is experimental for other operative systems. The version used in this book is the 15.10 (Wily Werewolf), and you can download it for free from http://releases.ubuntu.com/15.10. Note that you can also use Ubuntu 16.04 (Xenial), following the same steps shown here; indeed, for the BeagleBone Black installation we will use Ubuntu Xenial.
  • 43. Before starting with the installation, we are going to learn about the origin of ROS and its history. The Robot Operating System (ROS) is a framework that, nowadays, is widely accepted and used in the robotics community. Its main goal is to make the multiple components of a robotics system easy to develop and share so they can work on other robots with minimal changes. This basically allows for code reuse, and improves the quality of the code by having it tested by a large number of users and platforms. ROS was originally developed in 2007 by the Stanford Artificial Intelligence Laboratory (SAIL) in support of the Stanford AI Robot project. Since 2008, Willow Garage continued the development, and recently Open Source Robotics Foundation (OSRF) began to oversee the maintenance of ROS and partner projects, like Gazebo, including the development of new features. A lot of research institutions have started to develop in ROS, adding hardware and sharing their code. Also, companies have started to adapt their products to be used in ROS. In the following set of images, you can see some of the platforms that are fully supported. Normally, these platforms are published with a lot of code, examples, and simulators to permit the developers to start work easily. The first three humanoid robots are examples of robots with published code. The last one is an AUV developed by the University of Las Palmas de Gran Canaria, and the code has not been published yet. You can find many other examples at http://wiki.ros.org/Robots.
  • 44. Most of the sensors and actuators used in robotics are supported by ROS as drivers. Furthermore, some companies benefit from ROS and open hardware to create cheaper and easier to use sensors, as existing software can be used for them at zero cost. The Arduino board is a good example because you can add many different kinds of sensors to this cheap electronic board, such as encoders, light and temperature sensors, and many others, and then expose their measurements to ROS to develop robotic applications. ROS provides a hardware abstraction, low-level device control with ROS control, implementations of commonly used functionalities and libraries, message passing between processes, and package management with catkin and cmake. It uses graph architecture with a centralized topology, where processing takes place in nodes that may receive and send messages to communicate with other nodes on the graph net. A node is any process that can read data from a sensor, control an actuator, or run high level, complex robotic or vision algorithms for mapping or navigating autonomously in the environment. The *-ros-pkg is a community repository for developing high-level libraries easily. Many of the capabilities frequently associated with ROS, such as the navigation library and the rviz visualizer, are developed in this repository. These libraries provide a powerful set of tools for working with ROS easily; visualization, simulators, and debugging tools are among the most important features that they have to offer. In the following image you can see two of these tools, the rviz and rqt_plot. The screenshot in the center is rqt_plot, where you can see the plotted data from some sensors. The other two screenshots are rviz; in the screenshot you can see a 3D representation of a real robot.
  • 45. ROS is released under the terms of the Berkeley Software Distribution (BSD) license and is an open source software. It is free for commercial and research use. The ros-pkg contributed packages are licensed under a variety of open source licenses. With ROS, you can take a code from the repositories, improve it, and share it again. This philosophy is the underlying principle of open source software. ROS has numerous versions, the last one being Indigo. In this book, we are going to use Kinetic because it is the latest version. Now we are going to show you how to install ROS Kinetic. As we mentioned before, the operating system used in the book is Ubuntu, and we are going to use it throughout this book and with all the tutorials. If you use another operating system and you want to follow the book, the best option is to install a virtual machine with a copy of Ubuntu. At the end of this chapter, we will explain how to install a virtual machine to use the ROS inside it, or download a virtual machine with ROS installed. If you want to try installing it on an operating system other than Ubuntu, you can find instructions on how to do so with many other operating systems at http://wiki.ros.org/kinetic/Installation. PC installation
  • 46. We assume that you have a PC with a copy of Ubuntu 15.10. It will also be necessary to have a basic knowledge of Linux and command tools such as the terminal, Vim, folder creation, and so on. If you need to learn these tools, you can find a lot of relevant resources on the Internet, or you can find books on these topics instead.
  • 47. Installing ROS Kinetic using repositories Last year, the ROS web page was updated with a new design and a new organization of contents. The following is a screenshot of the web page: In the menu, you can find information about ROS and whether ROS is a good choice for your system. You can also find blogs, news, and other features. Instructions for ROS installation can be found under the Install tab in the Getting Started section. ROS recommends that you install the system using the repository instead of the source code, unless you are an advanced user and you want to make a customized installation; in that case, you may prefer installing ROS using the source code. To install ROS using the repositories, we will start by configuring the Ubuntu repository in our system.
  • 48. Configuring your Ubuntu repositories In this section, you will learn the steps for installing ROS Kinetic in your computer. This process has been based on the official installation page, which can be found at http://wiki.ros.org/kinetic/Installation/Ubuntu. We assume that you know what an Ubuntu repository is and how to manage it. If you have any doubts about it, refer to https://help.ubuntu.com/community/Repositories/Ubuntu. Before we start the installation, we need to configure our repositories. To do that, the repositories need to allow restricted, universe, and multiverse. To check if your Ubuntu accepts these repositories, click on Ubuntu Software Center in the menu on the left-hand side of your desktop, as shown in the following screenshot: Click on Edit | Software Sources and you will see the following window. Make sure that all the listed options are checked as shown in the following screenshot (choose the appropriate country for the server from which you download the sources):
  • 49. Normally these options are marked, so you should not have any problem with this step. Setting up your source.list file In this step, you have to select your Ubuntu version. It is possible to install ROS Kinetic in various versions of the operating system. You can use any of them, but we recommend version 15.10 to follow the chapters of this book. Keep in mind that Kinetic works in the Wily Werewolf (15.10) and Xenial Xerus (16.04) versions of Ubuntu. Type the following command to add the repositories: sudo sh -c 'echo "deb http://packages.ros.org/ros/ubuntu $(lsb_release - cs) main" > /etc/apt/sources.list.d/ros- latest.list'
  • 50. Other documents randomly have different content
  • 51. lessons on hearts which are really bleeding. Let such groan at liberty, and attempt not to contradict nature. Solitude may exalt the imagination; but it also inspires consoling ideas. In the silence of its refuge the desolate mourner brings himself to a nearer communion with him he regrets. He invokes, sees, and addresses him. Grief is more ingenious than we imagine in finding consolation, and has learned to employ different remedies according as the wounds are slight or deep. Two persons have each lost a dear friend. The one studiously avoids the places where he used to meet his friend. The other repairs to his desolate haunts, and surrounding himself by monuments associated with his memory, he seeks, if I may so say, to restore him to life. The death of a beloved wife is, perhaps, the most inconsolable of evils. Let this follow a series of other misfortunes, and it so effaces their remembrance that the sufferer feels he has not until then known real grief. But if this affliction be one under which our strength is broken, let it be the only one to obtain this fatal triumph. Under all other misfortunes we may find in ourselves resources for sustaining them; and may invariably either evade or assuage them, or mitigate their bitterness by resignation. Moralists have expatiated upon the manner in which a sage ought to contemplate the evils of life. Instead of subscribing to their trite maxims, often more imposing than practicable, I sketch a summary of my philosophy. I caution the feeble and erring beings that surround me, not to dream of unmixed happiness. I invite them to partake promptly of all innocent pleasures. The evils too often appended to them may follow. Know nothing of those which have no existence except in opinion. Struggle with courage to escape all that may be evaded. But if it become inevitable to meet them, let resignation, closing your eyes on the past, secure the repose of patient endurance when happiness exists for you no longer. Permit me to give these ideas some development. If I may believe the most prevalent modern philosophy, tranquillity of mind is the result of organization, or temperament, and of circumstances. It is
  • 52. the burden of my inculcation, that it may be of our own procuring; and that we owe it still more to the masculine exercise of our reason, discipline, and mental energy, than to our temperament or condition. We have reason to deplore that unhappy being, who, yielding to dreams of pleasure, forgets to forearm himself against a fatal awakening. The history of great political convulsions, and, more than all, that of the French revolution furnishes impressive examples of this spectacle. It offers more than one instance, in the feebler sex, of persons, who seemed created only to respire happiness. To the advantages of youth, talent and beauty, were united the most exalted rank, and wealth, pleasure and power, apparently to the extent of their wishes. To the dazzling fascination, with which a brilliant crowd surrounded their inexperience, many of them united the richer domestic enjoyments of the wife and mother. In the midst of their illusions, the revolutionary shout struck their ear, like a thunderstroke. Executioners bade them ascend the scaffold.[12] These great catastrophes, I know, are rare. But there will never cease to be sorrows, which will receive their last bitterness only in death. They are all too painful to be sustained, unless they have been wisely foreseen. Let us think of misfortune, as of certain characters, with whom our lot may one day compel us to consort. It is novelty alone, which gives our emotions extreme keenness. Whoever has strength of character, may learn to endure anything. The red men of the American wilderness are most impressive examples of this truth. Time, however, is the most efficacious teacher of the lesson of endurance. Poussin, in his painting of Eudomidas, has delineated the human heart with fidelity. The young girl of the piece abandons herself to despair. Half stretched upon the earth, her head falls supinely on the knees of the aged mother of the dying. This mother is sitting. Her attitude announces mingled meditation and grief. Amidst her tears, we trace firmness on her visage. One of the two women is taking her first lesson of misery.
  • 53. The other has already passed through a long apprenticeship of grief. [13] Reflection imparts anticipated experience. It takes from misery that air of novelty, which renders it terrible. When a wise man experiences a reverse, his new position has been foreseen. He has measured the sorrows, and prepared the consolations. Into whatever scene of trial he is brought, he will show in no one the embarrassment of a stranger. Taught to be conscious that we are feeble combatants, thrown upon an arena of strife, let us not calculate that destiny has no blows in store for us. Let us prepare for wounds, painful and slow to heal. Let us blunt the darts of misfortune in advance. Then, if they strike they will not penetrate so deep. But in premeditating the trials, which may be in reserve for our courage, let not anticipated solicitude disturb the present. Of all mental efforts, foresight is the most difficult to regulate. If we have it not, we fall into reverses unprepared. If we exercise it too far, we are perpetually miserable by anticipation. The philosopher prepares himself for contingent perils by processes which impart a keener pleasure to present enjoyment. He better understands the value of the moments of joy, and learns to dispel the fears, which might mar their tranquillity. That is a gloomy wisdom, which condemns the precepts that invite us to draw, from the uncertainty of our lot, a motive to embellish the moment of actual happiness. Transient beings, around whom everything is changing and in motion, adopt my maxims. Let us aid those who surround us, to put them in practice. Let us render those who are happy today more happy. Tomorrow the opportunity may have passed forever. As though nature had not sowed sufficient sorrows in our path during our short career, we have added to the mass by our own invention. The offspring of our vanity and puerile prejudices, these factitious pains seem sometimes more difficult to support, than real evils. A warrior, who has shown fearless courage in the deadly
  • 54. breach, has passed a sleepless night, because he was not invited to a party, or a feast; or because a riband, or a diploma has not been added to the many, with which he is already decorated. I had been informed, that the wife and son of a distinguished acquaintance were dangerously sick. I met him pale, and thoughtful. I was meditating, how to give him hope in regard to the objects of his supposed anxiety. While I was hesitating how to address him, he made known the subject of his real inquietude. He was in expectation of a high employment. The man of power, in whose hand was the gift, had just received him coldly a second time. He was anxiously calculating his remaining chances, and striving to divine the causes of his discouraging reception. To avoid such ridiculous agonies, let us adopt a maxim, not the less true, because the phrase, in which I express it, may seem trivial. Three quarters and half the remaining quarter of our vexations are not worth wasting a thought upon their cause. I add, that even in expectations which appear important, we ought to fear trusting too little to chance. The order of events, which we call by this name, is often more sage than any that human calculation can arrange. If it decides in a manner which at first view seems greatly against us, let us defer our accusations, until we have more thoroughly tested the event. I have met a man, who had long been an aspirant for a certain place, with a radiant countenance, having just obtained it. Three months afterwards, he would have purchased at any price the power of recalling events. I have seen another friend in desolation, because he could not obtain the hand of the daughter of a man, whose enterprises promised an immense fortune. He had been rejected. The speculations of her father all failed; and the reputation of his integrity and good faith with them. The despairing lover would have shared the poverty and disgrace of a helpless family; and would have been tormented, besides, with an incompatible union, of itself sufficient to have rendered him miserable in the midst of all the expected prosperity. One event is contemplated with a charmed eye; another with despair. The issue alone can declare, which of the two we ought to have desired.
  • 55. I grant, that we are surrounded by real dangers. I pretend not to be above suffering; and I attach no merit to becoming the reckless dupe of men or chance. The highest philosophy is at the same time the most simple and practicable. There is no error more common than one, which is taken for profound wisdom. Most men look too deep for the springs of events, and the motives of action. In many alternatives, we shall be most wise in giving the reins to chance. When we are menaced by an evident peril, let us summon all our energy, and courageously struggle to ward it off. If, after all, neither wisdom can evade it, nor bravery vanquish it, let us see, how true wisdom ordains us to sustain it. How many are ignorant of the value of resignation, or confound it with weakness! The courage of resignation is, perhaps, the most high and rare of all the forms of that virtue. Man received the gift directly from the Author of his being. His desires, inquietudes, misguided opinions, the fruits of an ambitious and incongruous education, have weakened its force in the soul. Who can read the anecdote of the American wilderness without thrilling emotion? An Indian, descending the Niagara river, was drawn into the rapids above the sublime cataract. The nursling of the desert rowed with incredible vigor at first, in an intense struggle for life. Seeing his efforts useless, he dropped his oars, sung his death song, and floated in calmness down the abyss. His example is worthy of imitation. While there is hope, let us nerve all our force, to avail ourselves of all the chances it suggests. When hope ceases, and the peril must be braved, wisdom counsels calm resignation.[14] In regard to unconquerable evils, the true doctrine is not vain resistance, but profound submission. It conceals the outline of what we have to suffer, as with a veil. It hastens to bring us the fruit of consoling time. It opens our eyes to a clearer view of the possessions which remain to us. It precedes hope, as twilight ushers in the day. It is by laying down certain well ascertained principles of conduct, and re-examining them every day, that a new empire is given to
  • 56. reason, and that we learn to select the most eligible point in all situations in life. The Greek philosophers were, incontestably, the men, who best understood the art of becoming happy. Their studies led them to the unwearied contemplation of the true good, the advantages of elevation of mind, the danger of the passions, and a calm submission to inevitable ills. Such were the habitual subjects of their meditations and discourses. They suffered less from the evils of life, only because they cultivated habits of profound reflection. Among the moderns, in pursuit of happiness, some study only to multiply their physical enjoyments; and limited to gross sensations, differ little from brutes, except in discoursing about what they eat. Others, higher in the scale of thought, cultivate the pleasures of literature and the fine arts. But disciplining but a single class of their powers, with a view to distinguish themselves from the vulgar, they are not always more happy. True philosophy is chiefly conversant about that kind of acquisition, which preëminently constitutes the rational man, forms his reason, and places him, as a master, in the midst of an unreflecting world surrounded by children full of ignorance and fatuity.
  • 58. L E T T E R V I I I . O F I N D E P E N D E N C E . We distinguish many kinds of liberty. That which we owe to equal laws, without being indispensable to a philosopher, renders the attainment of happiness more easy to him. However men differ in their political opinions, they all have an instinctive desire to be free. Every one is reluctant and afraid to submit himself to the capricious power of those about him. The thirst of power is only another form of this ardor for independence. With what interest we read in history of those ignorant tribes, unknown to fame, whose liberty and simple manners at once astonish and delight us? When visiting the isles of Greece, where the charm of memory rendered the view of their actual slavery more revolting, what delight the traveller experiences in traversing the little isle of Casos which had never submitted to the Ottoman yoke! He there found the usages of the ancient Greeks, their costume, their beauty and their amiable and elevated natural manner. This isle is but a rock. But its dangerous shores have defended it against tyranny. Associations with the songs of Homer and Hesiod are renewed. Such a picture delights even a people whose manners are refined to a degree tending to depravation. Thus those opulent citizens who find the country a place of exile still decorate their splendid halls with landscapes and flowers. Let not a sensitive and wandering imagination kindle too readily at the recitals of travellers. Were we to transport ourselves to one of those remote points of the earth where felicity is represented to have chosen her asylum, new usages, manners and pleasures, and a foreign people every moment reminding us that we are strangers, would, perhaps, give birth to the most painful regrets. When in our youth we were charmed as we read of the prodigies of Athens and Rome, we uttered the wish that we had been born in those
  • 59. renowned republics. There is little doubt that, had our wish been realized, we should be glad to escape their storms, in exchange for obscurely tranquil days. It is a distinguished folly which impels men far from their country in search of happiness. The greater portion, deceived in their hopes after having wandered amidst danger, die with regret and sorrow, worn out with vexation resulting from the broken ties and remembrances of home. Home is the last thought that comes over the departing mind. ‘Et dulces moriens reminiscitur Argos.’ Ubi patria ibi bene is an adage which contains as much wise observation as elevated patriotism. Our country is our common mother. We ought to love and sustain her more firmly in her misery than in her prosperity. Whatever manners, opinions and talents we carry into another country, we are still strangers there. The manners which we adopt are new and irksome. The eye sees nothing to awaken dear and embellished remembrances; and we find in the heart of no one the reverberating chord of ancient friendship and sympathy. We always regret the places where we knew the first pleasures and the first pains, and saw the first enchanting visions of life; the cherished spots where we learned to love and be loved. If, returning there, drawn back by an invincible sentiment, after a long absence we see it again, what sorrows await us! We find ourselves strangers in our own country. We ask for our parents and friends who departed in succession. The blows were struck at long intervals. We receive them all in a moment. We return to shed tears only on the tombs of our fathers![15] Retreat and competence everywhere supply a wise man a degree of independence. Even when the sport of oppression and injustice, he yields to these evils as the caprices of destiny. He would be free in the midst of Constantinople under the government of the Sultan. Another kind of liberty is the portion of but a few in our own country—the liberty of disposing of our whole time at our choice. To those who understand not the value of time, this liberty bequeaths a heavy bondage. But to those who have learned the secret of
  • 60. happiness it is of inestimable value. The privilege of the favored possessor of opulence is a high one. Neither the slave of business, fashion, opinion or routine, it is in his power at awaking to say ‘this day is all my own.’[15a] But moralists exclaim, ‘you must pay your debt: you must render yourselves useful to society.’ Let me not be understood to inculcate the doctrine of indolence. Industry will have wings and power when you unite it to freedom. But how many repeat the hackneyed cry of ‘the debt to society,’ who, in the choice of their profession, had never a thought but of its honors and emoluments! This man whose industry in the pursuit of his choice proves that his toil is his pleasure, that man who is in earnest to serve every one whom he can oblige and who might have shone, had he chosen it, in the career of ambition, but who, modest, proud, studious and free, lives happily in the bosom of retreat, has this man done nothing to acquit his debt? Is his example useless to society? If my condition deny me leisure and independence in regard to the disposal of my time, without bestowing much concern upon the choice of my profession, I should choose that most favorable to free thoughts, to breathing the open air, and, as much as might be, in view of a beautiful nature. I should consider it as a most important element in my happiness that I should be chiefly conversant with people of compatible characters. The profession of an advocate, perpetually conversant with the follies, vices and crimes of society, is one of the most trying, both to integrity and philosophy. That of the physician, continually witnessing groans, tears and physical suffering, however painful to sensibility, may become the source of high reflected pleasure to a generous and humane heart. I would avoid a function the disquieting responsibility of which would disturb my sleep. Above all, I should dread one of high honor and emolument, connected with proportionate uncertainty of tenure. The balance of enjoyment being taken into view, I should prefer an occupation of privacy. It would be more easy at once to obtain and preserve. It would expose me less to envy and competition.
  • 61. Exempt from the inquietudes inspired by severe labors, and the ennui of important etiquette, I should at least find an absolute independence, every evening, at the relinquishment of my daily routine of occupation, and I should suffer no care for the morrow; I would learn to enhance the charms of my condition by thinking of the agitation, regrets and alarms of those who are still swept by the whirlwinds of life. In this way I would imitate him who, to procure a more delicious repose, placed his couch under a tent near the sea, to be lulled by the dashing of its waves and the noise of its storms. But it is time to contemplate the most useful kind of liberty, the only indispensable kind, and happily one which is accessible to all. It is the liberty resulting from self-command and inward mastery of ourselves. It has a value to cause all others to be forgotten—a value which no other kind can replace. What liberty can that man enjoy who is the slave of ambition? A gesture, a look of the eye, a smile affrightens him and causes him painful and trembling calculations what that sinister sign of his master may presage. Look at the opulent merchant whose hopes are the sport of the winds, seas, robbers, changes of trade, municipal regulations, and a crowd of agents who seem subordinate, but who really command him. Whatever kind of liberty we aim to possess, we may certainly conclude that the surest means to enjoy it is to have few wants. But how restrain our wants? The greater portion are happily placed by their condition where they are ignorant of the objects which most powerfully excite and seduce desire. The golden mean secludes them from many temptations full of the bitterest regret, and exacts of them little effort of wisdom. In the class of men of leisure and elevated mind there are two means of rising above many wants. The more austere philosophers have altogether disdained those pleasures which they could never hope to obtain. Reducing themselves to the limits of the strictest necessity, they indemnify themselves for some privations by the certainty of being secured
  • 62. from many pains, and by the sentiment of conscious independence. This is, doubtless, one of the surest means of obtaining independence; and they who attempt to employ any other, differ from the vulgar by their principles rather than their conduct. How many objects, of which the contemplation awakens the desires, would have nothing dangerous if we could always exercise a stern self-control over our minds! The surest means of exercising this self-control is to reduce the number of our wants. To do it, I admit, demands a rare elevation of mind and the exercise of a high degree of philosophy. But since its value is beyond its cost, let us dare to acquire it. While the fleeting dreams of pleasure hover around us, let reason still say to us, ‘an instant may dissipate them.’ Let us, then, be ready to find a new pleasure in the consciousness of our firmness and our masculine and vigorous independence. An enlightened mind reigns over pleasures; and while they glitter around, enjoys all that are innocent; but disdains a sigh or a regret when they have taken wings and disappeared. I commend the example of Alcibiades, the disciple of the graces and of wisdom, who astonished in turn the proud Persian by his dignity, and the Lacedemonian by his austerity. His enemies may charge him with incessant change of principle. To me he seems always the same, always superior to the men and circumstances that surround him. Such strong mental stamina resemble those robust plants that sustain, without annoyance, the extremes of heat and cold.
  • 64. L E T T E R I X . O F H E A L T H . Health results from moderation, gayety and the absence of care. Eternal wisdom has ordained, that the emotions which disturb our days, are those which have a natural tendency to shorten them.[16] If there were ground for a single charge against the justice of nature, it would be, that the errors of inexperience seem punished with too great severity. We prodigally waste the material of life and enjoyment, as we do our other possessions, as if we thought it inexhaustible. To the errors of youth succeed the vices of mature age. Ambition and cupidity, envy and hatred concur to devour the very aliment of life. The storms which prostrate the moral faculties, equally sap the physical energy. Every debasing passion is a consuming poison. To what other source of evil can we assign those inquietudes and puerile anxieties, which disturb the days of the greater portion of mankind? They are occupied by trifling interests, and agitated by vain debates. They watch for futile excitements, and are in desolation from chimerical troubles. Pleasant emotions sustain life, and produce upon it the effect of a gentle current of air upon flame. Trains of thought habitually elevated, and sometimes inclined to revery, impart pure and true gayety to the soul. To be able to command this train is one of the rarest felicities of endowment. A distinguished physician recorded in his tablets the apparent paradox, that three quarters of men die of vexation or grief. Huffland has published a work, upon the art of prolonging life, full of interesting observations. ‘Philosophers,’ says he, ‘enjoy a delightful leisure. Their thoughts, generally estranged from vulgar interests, have nothing in common with those afflicting ideas, with which other men are continually agitated and corroded. Their reflections are agreeable by their variety, their vague liberty, and sometimes even
  • 65. by their frivolity. Devoted to the pursuits of their choice, the occupations of their taste, they dispose freely of their time. Oftentimes they surround themselves with young people, that their natural vivacity may be communicated to them, and, in some sort, produce a renewal of their youth.’ We may make a distinction between the different kinds of philosophy, in relation to their influence upon the duration of life. Those which direct the mind towards sublime contemplations, even were they in some degree superstitious, such as those of Pythagoras and Plato, are the most salutary. Next to them, I place those, the study of which, embracing nature, gives enlarged and elevated ideas upon infinity, the stars, the wonders of the universe, the heroic virtues, and other similar subjects. Such were those of Democritus, Philolaus, Xenophanes, the Stoics, and the ancient astronomers.’ ‘I may cite next those less profound thinkers, who instead of exacting difficult researches, seemed destined only to amuse the mind; the followers of which philosophy, deviating wide from vulgar opinion, peaceably sustain the arguments for and against the propositions advanced. Such was the philosophy of Carneades and the Academicians, to whom we may add the Grammarians and Rhetoricians.’ ‘But those which turn only upon painful subtilties, which are affirmative, dogmatic and positive, which bend all facts and opinions to form and adjust them to certain preconceived principles and invariable measures; in fine, such as are thorny, arid, narrow and contentious, these are fatal in tendency, and cannot but abridge the life of those, who cultivate them. Of this class was the philosophy of the Peripatetics, and that also of the Scholastics.’ Tumultuous passions and corroding cares are two sources of evil influences, which philosophy avoids. Another influence, adverse to life, is that mental feebleness, which renders persons perpetually solicitous about their health, effeminate and unhappy. Fixing their thoughts intensely on the functions of life, those functions, that are subjects of this anxious inspection, labor. Imagining themselves sick,
  • 66. they soon become so. The undoubting confidence that we shall not be sick, is perhaps the best prophylactic for preserving health. I am ignorant of the exact influence of moral upon physical action, in relation to health. But of this I am confident, that it is prodigious; that physicians have not made it a sufficient element in their calculations, or employed it as they should; and that in future, under a wise and more philosophic direction, it may operate an immense result, both in restoring and preserving health. A man reads a letter, which announces misfortunes, or sinister events. His head turns. His appetite ceases. He becomes faint, and oppressed; and his life is in danger. No contagion, however, no physical blow has touched him. A thought has palsied his forces in a moment; and has successively deranged every spring of life. We have read of persons of feeble and uninformed mind, who have fallen sick, in consequence of the cruel sport of those, who have ingeniously alarmed their imagination, and cautiously indicated to them a train of fatal symptoms. Since imagination can thus certainly overturn our physical powers, why may it not, under certain regulations, restore them? Among the numberless recorded cases of cures, reputed miraculous, it is probable, that a great part may be accounted for on this principle.[17] Suppose a paralytic disciple of the school of miracles, whose head is exalted with ideas of the mystic power of certain holy men, and who is meditating on the succor which he expects from a divine interposition manifested in his favor. In an ecstasy of faith, he sees a minister of heaven descend enveloped in light, who bids him ‘arise, and walk.’ In a moment the unknown nervous energy, excited by the mysterious power of faith, touches the countless inert and relaxed movements. The man arises and walks. During the siege of Lyons, when bombs fell on the hospital, the terrified paralytics arose and fled. I am not disposed to question all the cures, which in France have been attributed to magnetism. We know, what a salutary effect the sight of his physician produces on the patient, who has confidence in
  • 67. him. His cheerful and encouraging conversations are among the most efficient remedies. If we entertained a long cherished and intimate persuasion, that by certain signs, or touches, he could dispel our complaints, his gestures would have a high moral and physical influence. Magnetism was in this sense, as Bailly justly remarked, a true experiment upon the power of the imagination. At the moment of its greatest sway, while some regarded it an infallible specific, and others deemed it entirely inefficient, another class held it in just estimation. I cite an extract from the report of the Academy of Science. ‘We have sought,’ say they, ‘to recognise the presence of the magnetic fluid. But it escaped our senses. It was said, that its action upon animated bodies was the sole proof of its existence. The experiments, which we made upon ourselves, convinced us, that, as soon as we diverted our attention, it was powerless. Trials made upon the sick taught us, that infancy, which is unsusceptible of prejudice experienced nothing from it; that mental alienation resisted the action of magnetism, even in an habitual condition of excitability of the nerves, where the action ought to have been most sensible. The effects which are attributed to this fluid, are not visible, except when the imagination is forewarned, and capable of being struck. Imagination, then, seems to be the principle of the action. ‘It remained to be seen, whether we could reproduce these effects by the influence of imagination alone. We attempted it, and fully succeeded. Without touching the subjects, who believed themselves magnetised, and without employing any sign, they complained of pain and a great sensation of heat. On subjects, endowed with more excitable nerves, we produced convulsions, and what they called crises. We have seen an exalted imagination become sufficiently energetic to take away the power of speech in a moment. At the same time, we proved the nullity of magnetism, put in opposition with the imagination. Magnetism alone, employed for thirty minutes, produced no effect. Imagination put in action produced upon the
  • 68. same person, with the same means, in circumstances absolutely similar, a strong, and well defined convulsion. ‘In fine, to complete the demonstration, and to finish the painting of the effect of the imagination, a power equally capable of agitating, and calming, we have caused those convulsions to cease by the same power, which produced them—the power of the imagination. ‘What we have learned, or, at least what has been confirmed to us in a demonstrative and evident manner, by examination of the processes of magnetism is, that man can act upon man at every moment and almost at will, by striking his imagination; that signs and gestures the most simple may have effects the most powerful; and that the influence which may be exerted upon the imagination, may be reduced to an art, and conducted by method.’ These truths had never before acquired so much evidence. We know, that cures may be wrought by the single influence of imagination. Ambrose Paré Boerhaave, and many other physicians, have cited striking proofs of this fact. The first of these writers procured abundant sweats for a patient, in making him believe that a perfectly inert substance given him, was a violent sudorific. It is worthy of the attention of moralists and physiologists, as well as physicians, to examine, to what point we may obtain salutary effects, by exciting the imagination. But perhaps, there would soon be cause to dread the perilous influence of this art, which can kill, as well as make alive. This excitable and vivid faculty is never more easily put in operation, that when acted upon by the presentiments of charlatanism and superstition. We possess another means of operation, which may be exercised without danger, and the power of which is, also, capable of producing prodigies. Education rendering most men feeble and timid, they are ignorant, how much an energetic will can accomplish. It is able to shield us from many maladies; and to hasten the cure of those under which we labor.
  • 69. In mortal epidemics, the physicians, who are alarmed at their danger, are ordinarily the first victims. Fear plunges the system into that state of debility, which predisposes it to fatal impressions, while the moral force of confidence, communicating its aid to physical energy, enables it to repel contagion. I could cite many distinguished names of men, who attributed their cure, in desperate maladies, to the courage which never forsook them, and to the efforts which they made to keep alive the vital spark, when ready to become extinct. One of them pleasantly said, ‘I should have died like the rest, had I wished it.’[18] Pecklin, Barthes and others think that extreme desire to see a beloved person once more, has sometimes a power to retard death. It is a delightful idea. I feel with what intense ardor one might desire to live another day, another hour, to see a friend or a child for the last time. The flame of love, replacing that of life, blazes up for a moment before both are quenched in the final darkness. The last prayer is accorded; and life terminates in tasting that pleasure for which it was prolonged. If this be true, the principle on which the most touching incident of romance is founded, is not a fiction. I have no need to say that an energetic will to recover from sickness has no point of analogy with that fearful solicitude which the greater part of the sick experience. The latter, produced by mental feebleness, increases the inquietude and aggravates the danger. Even indifference would be preferable. If education had imparted to us the advantages of an energetic will and real force of mind, if from infancy we had been convinced of the efficacy of this moral power, we have no means to determine that it would not have been, in union with the desire of life, an element in the means of healing our maladies. Medicine is still a science so conjectural that the most salutary method of cure, in my view, is that which strives not to contradict nature, but to second her efforts by moral means. I am ready to believe that amidst the real or imagined triumphs of science, those of medicine will, in the centuries to come, hold a rank to which its
  • 70. past achievements will have borne no proportion. But what an immense amount of experiment will be necessary! How many unfortunate beings must contribute to the expense of these experiments! Contrary to the general opinion, I highly esteem physicians and think but very little of medicine. In the profession of medicine we find the greatest number of men of solid minds and various erudition; and the best friends of humanity. But they are in the habit of vaunting the progress of their science. To me it seems incessantly changing its principles, without ever varying its results. The systems of various great men have been successively received and rejected. Do we, however, imagine that the great physicians who have preceded us were more unfortunate in their practice than those of our days? Among the most eminent physicians of our cities, one practises by administering strong cathartics. Another is resolute for copious bleeding. A third bids us watch and wait the indications of nature. Each of these assumes that the system of the rest is fatal— and so, it would seem, it should be. At the end of the year, however, I doubt if any one of them all has more reproaches to make, as regards want of success, than any other. From these facts, there are those who hold that it is most prudent to confide to nature, as the physician; forgetful that, if he could bring no other remedy than hope, he unites moral to physical aid. Yet, the very persons who, in health are readiest to maintain this doctrine, like children who are heroes during the day but cowards in the dark, when they are sick, are as prompt as others in sending for the physician. Even if agitation and fear had not fatal effects, in rendering us more accessible to maladies, wisdom would strive to banish them, in pursuit of the science of happiness. Fear, by anticipating agony, doubles our sufferings. If there could exist a rational ground for continual inquietude, it would be found in a frail constitution. But how many men of the feeblest health survive those of the most
  • 71. vigorous and robust frame! Calculations upon the duration of life are so uncertain that we can always make them in our favor. To him who cultivates a mild and pleasant philosophy, old age itself should not be contemplated with alarm. It may seem a paradox to say that all men are nearly of the same age, in reference to their chances of another day. Men are as confident of seeing tomorrow and the succeeding day, at eighty, as at sixteen. Such is the beautiful veil with which nature conceals from us the darkness of the future. In general, men have less sympathy for the suffering than their condition ought to inspire. We meet them with a sad face and are more earnest to show them that we are afflicted ourselves, than to seek to cheer their dejection. We multiply so many questions touching their health that it would seem as if we feared to allow them to forget that they were sick. Of all subjects of conversation, my own pains and physical infirmities have become the least interesting to me; as I know they must be to others. I do not wish that those who surround my sick bed should converse as though arranging the preparations for my last dress, or determining the hour of my interment. If we would live in peace, and die in tranquillity, let us, as much as possible, avoid importunate cares. Our business is to unite as many friends as we may; and to beguile pain and sorrow by treasuring as many resources of innocent amusement as our means will admit. If our sufferings become painful and incurable, we must concentrate our mental energy and settle on our solitary powers of endurance. We die, or we recover. Nature, though calm, moves irresistibly to her point; and complaint is always worse than useless.[19] But in arming ourselves with courage to support our own evils, let us preserve sensibility and sympathy for the sufferings of others. It is among the dangerously sick that we find those unfortunate beings who are most worthy to inspire our pity. Their only expectation is death, preceded by cruel tortures; and yet they, probably, suffer less for themselves than for weeping dependents whom they are leaving,
  • 72. it may be, without a single prop. Ah! during the few days of sorrow that remain to them on the earth, how earnestly ought we to strive to mitigate their pains, to calm their alarms and animate their feeble hopes! Blessed be that beneficent being who shall call one smile more upon their dying lips![20]
  • 74. L E T T E R X . O F C O M P E T E N C E . Pretended sages announce to us, with sententious gravity, that virtue ought to be the single object of our desires; that, strengthened by it, we can support privations and misery without suffering. Useless moralists! Shall I yield faith to precepts which the experience of every day falsifies? It is only necessary, in refutation, to present a man who has broken his limb, or whose children suffer hunger. His plan is wise, who examines, with a judgment free from ambition, the amount of fortune necessary to competence in his case, viewed in all its bearings; and commences the steady pursuit of it. Having reached that measure, if his desires impel him beyond the limit which, in a more reasonable hour, he prescribed for himself, he henceforward strives to be happy by sacrificing enjoyment. He barters it for a very uncertain means of purchasing even pleasures. In this way competence becomes useless to the greater part of those who obtain it. Victims of the common folly, and still wishing a little more, they lose, in the effort to get rich, the time which they ought to spend in enjoyment. We see grasping and adroit speculators on every side; and, but rarely, men who know how to employ the resources of a moderate fortune. It is not the art of acquiring beyond competence, but of wisely spending, that we need to learn. Our business in life is to be happy; and yet, simple and obvious as this truism is, the greater number disdain or forget it. To judge from the passions and objects that we see exciting man to action, we should suppose that he was placed on the earth, not to become happy, but rich. To what purpose so many cares and studies? ‘That man,’ we are answered with a peculiar emphasis, ‘has an immense income.’ In his
  • 75. rare, brilliant and envied condition, if he does not vegetate under the weight of ennui, I recognise in him a man of astonishing merit. The opulent may be divided into two classes. The employment of the one is to watch over their expenditures. The other study the mode of dissipating their revenue. Can I present, in detail, the cares and vexations which an immense fortune brings? The possessor leaves discussion with his tenants, to commence angry disputes with his workmen. From these he departs to listen to the schemes of projectors, or to the information of advocates. Is not such a result dearly purchased at the expense of repose, independence and time? Would it not be better to relinquish a part of these possessions, in order to dispose, in peace, of the remainder? I admit that a man who devotes himself to lucrative pursuits is not overwhelmed with continual ennui. The banker respires again, after having grown pale over his accounts. A speculation has succeeded, and the enchantment of success banishes his alarms, fatigues and slavery. But he whose purpose in life is to secure as many happy moments as he can, and who sees how many innocent pleasures the other allows to escape him, would refuse his fortune at the price which he pays for it. Another opulent class inherit fortunes acquired by the industry and sacrifices of their fathers. Rendered effeminate in a school, the reverse of that in which their fathers were trained, without resources in themselves, accustomed from infancy to have their least desires anticipated, under the influence of feeble parents, pliant and servile instructers, greedy servants and a seducing world, their appetite is early palled, and every pleasure in life worn out. But suppose the rich heir brought up as though he were not rich, destiny places before him a strange alternative. If he succeed in resisting desires which everything excites and favors, what painful struggles! If he yield to them, what effort can preserve him an untainted mind? The experience of all time declares the improbability that he will resist. So many pretended friends are at hand to take up the cause of the present against the future, a cause,