In this post, we will see how to write a ROS program (in Python) to make a robot rotate according to user input. We are going to fix an error in the code that prevents this program from working as we go on.
PS:This ROS project is part of our ROS Mini Challenge series, which gives you an opportunity to win an amazing ROS Developers T-shirt! This challenge is already solved. For updates on future challenges, please stay tuned to our Twitter channel.
Step 1: Grab a copy of the ROS Project that contains the almost-working Python code
Click here to get your own copy of the project. If you don’t have an account on the ROS Development Studio, you will be asked to create one. Once you create an account or log in, the project will be copied to your workspace. That done, open your ROSject using the Open button. This might take a few moments, please be patient.
You should now see a notebook with detailed instructions about the challenge. Please ignore the section that says “Claim your Prize!” because, well, the challenge is closed already 🙂
Step 2: Start the Simulation and run the program
Click on the Simulations menu and then Choose launch file… . In the dialog that appears, select rotw1.launch, then click the Launchbutton. You should see a Gazebo window popup showing the simulation: a robot standing in front of a very beautiful house!
Keeping the Gazebo window in view, pick a Shell from Tools > Shelland run the following commands (input the same numbers shown):
user:~$ rosrun rotw1_code rotate_robot.py
Enter desired angular speed (degrees): 60
Enter desired angle (degrees): 90
Do you want to rotate clockwise? (y/n): y
[INFO] [1580744469.184313, 1044.133000]: shutdown time! Stop the robot
Did the robot rotate? I would be surprised if it did!
Step 3: Find out what the problem is (was!)
Fire up the IDE and locate the file named rotate_robot.py.You will find in the catkin_ws/src/rotw1_code/src directory.
#!/usr/bin/env python
import rospy
from geometry_msgs.msg import Twist
from sensor_msgs.msg import LaserScan
import time
class RobotControl():
def __init__(self):
rospy.init_node('robot_control_node', anonymous=True)
self.vel_publisher = rospy.Publisher('/velocity', Twist, queue_size=1)
self.cmd = Twist()
self.ctrl_c = False
self.rate = rospy.Rate(10)
rospy.on_shutdown(self.shutdownhook)
def publish_once_in_cmd_vel(self):
"""
This is because publishing in topics sometimes fails the first time you publish.
In continuous publishing systems, this is no big deal, but in systems that publish only
once, it IS very important.
"""
while not self.ctrl_c:
connections = self.vel_publisher.get_num_connections()
if connections > 0:
self.vel_publisher.publish(self.cmd)
break
else:
self.rate.sleep()
def shutdownhook(self):
self.stop_robot()
self.ctrl_c = True
def stop_robot(self):
rospy.loginfo("shutdown time! Stop the robot")
self.cmd.linear.x = 0.0
self.cmd.angular.z = 0.0
self.publish_once_in_cmd_vel()
def get_inputs_rotate(self):
self.angular_speed_d = int(
raw_input('Enter desired angular speed (degrees): '))
self.angle_d = int(raw_input('Enter desired angle (degrees): '))
clockwise_yn = raw_input('Do you want to rotate clockwise? (y/n): ')
if clockwise_yn == "y":
self.clockwise = True
if clockwise_yn == "n":
self.clockwise = False
return [self.angular_speed_d, self.angle_d]
def convert_degree_to_rad(self, speed_deg, angle_deg):
self.angular_speed_r = speed_deg * 3.14 / 180
self.angle_r = angle_deg * 3.14 / 180
return [self.angular_speed_r, self.angle_r]
def rotate(self):
# Initilize velocities
self.cmd.linear.x = 0
self.cmd.linear.y = 0
self.cmd.linear.z = 0
self.cmd.angular.x = 0
self.cmd.angular.y = 0
# Convert speed and angle to radians
speed_d, angle_d = self.get_inputs_rotate()
self.convert_degree_to_rad(speed_d, angle_d)
# Check the direction of the rotation
if self.clockwise:
self.cmd.angular.z = -abs(self.angular_speed_r)
else:
self.cmd.angular.z = abs(self.angular_speed_r)
# t0 is the current time
t0 = rospy.Time.now().secs
current_angle = 0
# loop to publish the velocity estimate, current_distance = velocity * (t1 - t0)
while (current_angle < self.angle_r):
# Publish the velocity
self.vel_publisher.publish(self.cmd)
# t1 is the current time
t1 = rospy.Time.now().secs
# Calculate current angle
current_angle = self.angular_speed_r * (t1 - t0)
self.rate.sleep()
# set velocity to zero to stop the robot
#self.stop_robot()
if __name__ == '__main__':
robotcontrol_object = RobotControl()
try:
res = robotcontrol_object.rotate()
except rospy.ROSInterruptException:
pass
The problem was in the def __init__(self) function – we are publishing to the wrong topic – /velocity – instead of /cmd_vel.
Next, let’s see how we found the problem.
Step 4: Learn how the problem was solved
If you’re familiar with ROS, you’ll know that /cmd_vel is the most common name for the topic responsible for moving the robot. It’s not always that, but at least the /velocity topic instantly became suspect! Therefore, we went ahead to examine it to see if it was a proper topic:
And our suspicions were confirmed: the topic had no subscribers. This was strange, as usually /gazebo would be one of the subscribers if it was connected to the simulation.
On the other hand, /cmd_vel was connected to /gazebo. So, maybe it’s the right topic after all, but let’s confirm that next.
Step 5: Replace /velocity with /cmd_vel and rotate the robot!
Replace /velocity with /cmd_vel in the def __init__(self) function and save.
Now run the program again:
user:~$ rosrun rotw1_code rotate_robot.py
Enter desired angular speed (degrees): 60
Enter desired angle (degrees): 90
Do you want to rotate clockwise? (y/n): y
[INFO] [1580744469.184313, 1044.133000]: shutdown time! Stop the robot
Now, the robot should rotate according to user input – try different numbers!
And that was it. Hope you found this useful.
Extra: Video of this post
We made a video showing how this challenge was solved. If you prefer “sights and sounds” to “black and white”, here you go:
Did you like this post? Do you have questions about what was explained? Whatever the case, please leave a comment on the comments section below, so we can interact and learn from each other.
If you want to learn about other ROS or ROS2 topics, please let us know in the comments area and we will do a video or post about it.
Head to http://rosds.online and create a project with a similar configuration as the one shown below. You can change the details as you like, but please make sure you select “Ubuntu 16.04 + ROS Kinetic + Gazebo 7” under “Configuration”.
Once done with that, open your ROSject. This might take a few moments, please be patient.
Step 2: Create a ROS package with a Python program
Pick a Shell from the Tools menu and create a Python package.
user:~$ cd catkin_ws/
user:~/catkin_ws$ cd src
user:~/catkin_ws/src$ catkin_create_pkg missing_permission
Created file missing_permission/package.xml
Created file missing_permission/CMakeLists.txt
Successfully created files in /home/user/catkin_ws/src/missing_permission. Please adjust the values in package.xml.
user:~/catkin_ws/src$ cd missing_permission/
user:~/catkin_ws/src/missing_permission$ mkdir -p src/
user:~/catkin_ws/src/missing_permission$ cd src
user:~/catkin_ws/src/missing_permission/src$ touch missing_perm.py
user:~/catkin_ws/src/missing_permission/src$
Fire up the IDE from the Tools menu, find the missing_perm.py file in the missing_permission package, open the file and paste the following code into it.
#! /usr/bin/env python
import rospy
rospy.init_node("Obiwan")
rate = rospy.Rate(2)
while not rospy.is_shutdown():
print "Help me Obi-Wan Kenobi, you're my only hope"
rate.sleep()
Save().
Step 3: Compile and source the workspace.
cd ~/catkin_ws
catkin_make
source devel/setup.bash
Step 4: Run the package with rosrun and roslaunch.
First, we check that the package has been recognized, with rospack list. Then we run it with rosrun.
user:~/catkin_ws$ rospack list | grep missing
missing_permission /home/user/catkin_ws/src/missing_permission
user:~/catkin_ws$ rosrun missing_permission missing_perm.py
[rosrun] Couldn't find executable named missing_perm.py below /home/user/catkin_ws/src/missing_permission
[rosrun] Found the following, but they're either not files,
[rosrun] or not executable:
[rosrun] /home/user/catkin_ws/src/missing_permission/src/missing_perm.py
user:~/catkin_ws$
The program did not run! What’s that error? Surely that not what we expected. Maybe rosrun does not like us – let’s try roslaunch!
Create a launch file and use it to launch the python program:
user:~/catkin_ws$ cd src/missing_permission/
user:~/catkin_ws/src/missing_permission$ mkdir -p launch
user:~/catkin_ws/src/missing_permission$ cd launch
user:~/catkin_ws/src/missing_permission/launch$ touch missing_perm.launch
user:~/catkin_ws/src/missing_permission$
Open the launch file in the IDE and paste in the following code:
user:~/catkin_ws/src/missing_permission$ cd ~/catkin_ws
user:~/catkin_ws$ source devel/setup.bash
user:~/catkin_ws$ roslaunch missing_permission missing_perm.launch
... logging to /home/user/.ros/log/e3188a2e-e921-11e9-8ac1-025ee6e69cec/roslaunch-rosdscomputer-11105.log
...
NODES
/
missing_permission_ex (missing_permission/missing_perm.py)
auto-starting new master
process[master]: started with pid [11147]
ROS_MASTER_URI=http://master:11311
setting /run_id to e3188a2e-e921-11e9-8ac1-025ee6e69cec
process[rosout-1]: started with pid [11170]
started core service [/rosout]
ERROR: cannot launch node of type [missing_permission/missing_perm.py]: can't locate node [missing_perm.py] in package [missing_permission]
Oops! It didn’t run again. Now we have another error screaming:
ERROR: cannot launch node of type [missing_permission/missing_perm.py]: can't locate node [missing_perm.py] in package [missing_permission]
What do we do now?
Step 5: Fix the missing execute permission on the Python file and be happy!
user:~/catkin_ws$ cd src/missing_permission/src/
user:~/catkin_ws/src/missing_permission/src$ chmod +x missing_perm.py
user:~/catkin_ws/src/missing_permission/src$
Now let’s try again with both roslaunch and rosrun:
user:~/catkin_ws/src/missing_permission/src$ roslaunch missing_permission missing_perm.launch
...
NODES
/
missing_permission_ex (missing_permission/missing_perm.py)
auto-starting new master
process[master]: started with pid [13206]
ROS_MASTER_URI=http://master:11311
setting /run_id to eec6e306-e922-11e9-b72a-025ee6e69cec
process[rosout-1]: started with pid [13229]
started core service [/rosout]
process[missing_permission_ex-2]: started with pid [13242]
Help me Obi-Wan Kenobi, you're my only hope
Help me Obi-Wan Kenobi, you're my only hope
Help me Obi-Wan Kenobi, you're my only hope
...
Running fine with roslaunch. Press Ctrl + C on the roslaunch program and try rosrun:
user:~/catkin_ws/src/missing_permission/src$ rosrun missing_permission missing_perm.py
Unable to register with master node [http://master:11311]: master may not be running yet. Will keep trying.
If you get the error above, please spin another Shell from the Tools menu, and run the following to start the ROS master:
user:~$ roscore
After this, the roscore command should resume and you’ll get:
user:~/catkin_ws/src/missing_permission/src$ rosrun missing_permission missing_perm.py
Unable to register with master node [http://master:11311]: master may not be running yet. Will keep trying.
Help me Obi-Wan Kenobi, you're my only hope
Help me Obi-Wan Kenobi, you're my only hope
Help me Obi-Wan Kenobi, you're my only hope
...
And that was it. As it turned out, roscore had no ill-feeling towards us!
Did you like this post? Do you have questions about what was explained? Whatever the case, please leave a comment on the comments section below, so we can interact and learn from each other.
If you want to learn about other ROS or ROS2 topics, please let us know in the comments area and we will do a video or post about it 🙂
ROS is becoming the standard of Robotics Programming and learning about ROS has also become more and more important. There are more and more courses taught using ROS. In this post you will find all upcoming ROS courses in 2018.
If you are teaching a course (at any level) using ROS please comment below and we’ll share it to this list.
Short Courses (Intensive Training):
Robot Operating System Summer School ROS 2018
FH Aachen University of Applied Sciences • Aachen
Dates:
August 20 – August 31, 2018 (Registration Deadline May 31, 2018)
Course Content:
The ROS Summer School provides the right starter kit in the form of our robotic hardware and – of course – ROS software. We start with several days of introductory courses before tackling the main task of mobile robotics, i.e., perception, localisation, and navigation.
A highlight of the programme is a competition at the end of the second week: summer school participants form several teams that are then given the task of designing a typical mobile robotic application such as indoor/outdoor exploration. They all use the same hardware, which is powered by the ROS skills that they have acquired.
Tokyo Opensource Robotics Kyokai • Tokyo and Aichi
Date:
May 17, 2018 (Venue : Yurakucho, Tokyo)
May 22, 2018 (Venue :Venue: Nagoya, Aichi)
About the course: Introductory course for ROS, a defacto standard robotics framework software. Suitable for professionals who heard “ROS” but never experienced yet.
RobotCraft 2018: Internship and Summer Course on Robotics
3rd Robotics Craftsmanship International Academy • Portugal
Date: Jul 2 – Sep 2, 2018
About the course:
Ingeniarius, University of Coimbra and Robotic Clube of UC provide internship mobility and a unique summer course in robotics to students, with or without Erasmus+ Internship mobility. The students attending this 2-months program will have the opportunity to work on robotics, focusing on several state-of-the-art approaches and technologies. The summer course, entitled as the 3rd Robotics Craftsmanship International Academy (RobotCraft 2018 – 2nd July 2018 to 2nd September 2018), will provide a general overview of the science and art behind robotics, teaching the basis around the Arduino programming and the ROS framework. Students will learn how to design, build and program their robots throughout multiple crafts, carefully prepared to provide a wide range of skills and knowledge on the topic.
About the course: It’s an online Academy contains a series of online ROS courses tied to online simulations, giving you the tools and knowledge to understand and create any ROS based robotics development.The topics include: ROS basics, navigation, manipulation,, perception, self-driving cars using ROS, ROS-Industrial, OpenAI Gym for robotics, Robot Creation with URDF ROS, RGB-Navigation, ROS control, TF, ROS deep learning with TensorFlow and programming drones with ROS.
International ACADEMY | RWTH-AACHEN University • Aachen
* Date:
17/09 – 21/09/2018
About the course:
ROS FOR INDUSTRIAL ROBOTS
This course introduces the ROS middleware and its tools for developing modern robot systems. It covers the general structure of ROS and the usage of its publish-subscribe, service and action-server concepts. Furthermore, a short introduction of the robot simulation GAZEBO is given. Within hands-on-sessions, the participants will integrate the key components of a mobile robot (Hardware, Sensory as well as Localization, Mapping and Motion Planning Algorithms) in ROS.
The course will be completed with an examination.
Affiliated to this, successful participants will receive the official RWTH Executive Certificate.
MECH_ENG 495: SELECTED TOPICS: EMBEDDED SYSTEMS IN ROBOTICS
Department of Mechanical Engineering – Northwestern University • USA
Date: Offered every fall quarter
About the course:
This is a project-based course aimed at providing experience with a variety of software tools that may be valuable to a robotics engineer working with practical embedded systems. The course will use the Robot Operating System (ROS) as an example framework for software architecture, and learning ROS will be a primary goal of this course. After introductory material, students will work in groups to complete software-intensive robotics projects that operate with real hardware.
University of Zagreb Faculty of Electrical Engineering and Computing • Croatia
Date: Winter semester
About the course: High complexity of tasks that the modern mobile robots are facing calls for using a programming infrastructure which enables efficient integration of independently developed subsystems into a single system enabling autonomous robot operation. The Robot Operating System (ROS) offers an environment for developing modular control software, a communication infrastructure to connect the software components and an open source library of implemented algorithms. In the last five years ROS has become the standard for robot control in the academic community and its influence is spreading also in the industry. In the scope of this course we shall cover the practical development of software modules in the ROS environment and their integration into a completely functional system for autonomous robot control.
Computer Science & Engineering Department – University of South Carolina • Columbia
Date: Spring 2018
About the course: In this course we will study the latest methods in Machine Learning as they apply to the field of robotics. In particular we will study: Reinforcement learning, Gaussian Processes, Deep Learning, and Deep Reinforcement Learning.
The Computational Learning and Motor Control Lab • USA
Date: Fall 2018
About the course: This course introduces fundamental concepts in Robotics. In the first half of the course, basic concepts will be discussed, including coordinate transformation, kinematics, dynamics, Laplace transforms, equations of motion, feedback and feedforward control, and trajectory planning. These topics will be exemplified with simulation studies using our own simulator. The second half of the course will focus on applying the knowledge from the initial lectures to various motor systems, including manipulators, artificial eye systems, locomotory systems, and mobile robotics. Some lectures will be replaced/supplemented with labs in which the course participant will learn to program a small humanoid robot.
Paul G. Allen School of Computer Science & Engineering – University of Washington • USA
Date: Winter 2018
About the course:The main goal of this course is to open up new career options in robotics for computer science and engineering students. To that end, the course will teach you the basics of robotics and give you implementation experience. You will learn to use libraries and tools within the most popular robot programming framework ROS (Robot Operating System). We will touch on robot motion, navigation, perception, planning, and interaction through mini-lectures, labs and assignments, eventually integrating these components to create autonomous or semi-autonomous robotic functionalities. The project will give you team-work experience with large scale software integration and it will get you thinking about opportunities for using robots to make people’s lives easier.
ROS (Robot Operating System) is a common robot software platform which intents to integrate the world’s robotics research energy, and is completely open source. Anyone could just install ROS and immediately get access to all the resources that ROS integrates.
Over the several years, ROS is growing faster than ever. It can be used not only in the laboratory but in the commercial and services industries. If you subscribe to some mailing list such as Robotics Worldwide, you could see that around 70% of robotics job offerings require ROS.
However, this system is huge and complex. There are over 3,000 packages in the ROS ecosystem, and those are constantly updated every day. It requires a lot of effort to learn ROS and it is relatively hard for a beginner.
If you Google it, you will find a full of variety of ROS learning resources, everyone implementing a different learning method. But which kind of learning method is most effective for you? Check the following 5 ROS learning methods and find the best one for you:
Official tutorials: ROS Wiki
The official ROS tutorial website provided by OSRF is very comprehensive and it is available in multiple languages. It includes details for ROS installation, documentation of ROS, ROS courses&events, etc. and it’s completely free. You just need to follow the ROS tutorials provided on ROS Wiki page, and get started.
This type of tutorial belongs to the traditional academic learning materials. They start by describing concepts one by one, following a well-defined hierarchy. It’s good material but easy to get lost while reading, and it takes time to grasp the core spirit of ROS.
ROS Video Tutorials:
ROS video tutorials provide a unique presentation which shows how programs are created and ran, in a practical way. It allows you to learn how to carry a ROS project from the professional or instructor, which alleviate a beginner’s fear to start learning ROS to a certain degree.
But there is a drawback that anyone can create a video, this means not require any sort of qualification to publish their content, credibility might be shifty.
One of the ROS video tutorial course provided by Dr. Anis Koubaa from Prince Sultan University, is a great starting point to learn ROS. The course combines a guided tutorial, different examples, and exercises with increasing level of difficulty along with an autonomous robot.
Integrated ROS learning platform – Robot Ignite Academy
The integrated learning platform is a more dynamic way of ROS learning. Compared to other learning methods, it provides a more comprehensive learning platform.
Thismethod makes the students forget as many concepts as possible and concentrate on doing things with the robots. You will learn ROS by practicing.
You will follow a step-by-step ROS tutorial and will program the robots while observing the program’s result on the robot simulation in real-time. The whole platform is integrated into a web page so you don’t have to install anything. You just connect by using a web browser from any type of computer and start learning.
Well, perhaps the only drawback is it is not free. You can try the platform for free inwww.robotigniteacdemy.com or watch their free video tutorials on YouTube.
Face-to-face ROS training
The face-to-face instructional course is the traditional way of teaching. It builds strong foundations of ROS into students.
ROS training is usually a short course, it requires you to focus on learning ROS in a particular environment and a period of time. With the interaction with teachers and colleagues which allows you to get feedback directly. Under the guidance and supervision of instructors, it definitely encourages a better result.
The following are some of the institutions that are holding offline ROS training or summer courses on a regular basis:
ROS books are published by experienced roboticists. They extract the essence of ROS and present a lot of practical examples.
Books are good tools for learning ROS, however, it requires high self-discipline and concentration so as to achieve the desired result. (but they are only as good as the person using them, it depends on many factors. It allows many distractions to easily affect your progress, unless the strong self-discipline to ensure is paying full attention at all times)
Some recommend readings:
Programming Robot with ROS: by combining real-world examples with valuable knowledge from the ROS community, this practical book provides a set of motivating recipes for solving specific robotics use cases.
ROS IN 5 DAYS Book Collection: a book collection associated with online ROS courses giving you the basic tools and knowledge to be able to understand and create any basic ROS related project.
ROS Robotics by Example: this book will help you boost your knowledge of ROS and give you advanced practical experience you can apply to your ROS robot platforms.
Do you have any other better ROS learning method? Please, comment to share it with us!