Ros turtlesim - arieldo/MorBot GitHub Wiki
Getting Started with turtlesim in ROS
- Introduction
- Prerequisites
- Start turtlesim
- Control the turtle using the turtle_teleop_key node
- Explore ROS topics in turtlesim
- Monitor the turtle's position
- Control the turtle programmatically
- Changing the Background Color of Turtlesim
- Moving the Turtlesim Based on Background Color
- Spawning a multiple Turtle in Turtlesim Window
Like any big engineering project, testing the system on a simulator before sending the real robot to the moon is a good practice.
In this tutorial, you'll learn how to use turtlesim, a simple Motion simulator. Turtlesim provides an easy way to learn ROS basics, such as publishing, subscribing, and services, by controlling a turtle in a 2D simulation environment.
To get the turtlesim package, you don't need to install it separately since it's included as part of the standard ROS installation. If you have ROS Melodic or Noetic installed on your system, you already have the turtlesim package.
- Familiarity with ROS concepts, such as nodes, topics, and messages, IF not Check out ROS 101
- Basic understanding How To Creating New Packages in ROS
- Learn to write a Simple Publisher and Subscriber in Python for ROS ROS PubSubPy
- Basic understanding of Python
To start turtlesim, open a terminal window, and run the following command:
roscore
This command starts the ROS Master, which manages communication between nodes. Now, open a new terminal window and run the following command:
rosrun turtlesim turtlesim_node
You should see a new window with a blue background, gridlines, and a turtle in the center. This is the turtlesim environment.
Open another terminal window and run the following command:
rosrun turtlesim turtle_teleop_key
Now, focus on the terminal window where you launched turtle_teleop_key
and use the arrow keys to control the turtle. You'll see the turtle moving around the turtlesim environment.
While the turtlesim is running, open another terminal window and run the following command to list available topics:
rostopic list
You will see several topics related to the turtlesim, such as /turtle1/cmd_vel
, /turtle1/color_sensor
, and /turtle1/pose
.
To see the turtle's position in real-time, subscribe to the /turtle1/pose
topic using the rostopic echo
command:
rostopic echo /turtle1/pose
As you move the turtle around using the arrow keys, you'll see its position, orientation, and linear/angular velocities updated in the terminal window.
-
Navigate to the
scripts
directory of yoursimple_pub_sub package
,~/MorBot/morbot_ros/morbot_ws/src/simple_pub_sub/scripts
Create a new source file namedmove_turtle.py
inside thescripts
directory.cd ~/MorBot/morbot_ros/morbot_ws/src/simple_pub_sub/scripts touch move_turtle.py chmod +x move_turtle.py
-
Open the
move_turtle.py
file in a text editor, and paste the following code:
#!/usr/bin/env python
# Import necessary modules
import rospy
from geometry_msgs.msg import Twist
# Define the move_turtle function
def move_turtle():
# Initialize the ROS node with a unique name
rospy.init_node('move_turtle', anonymous=True)
# Create a publisher object to publish messages to the /turtle1/cmd_vel topic
pub = rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size=10)
# Create a rate object to control the loop rate (1 message per second)
rate = rospy.Rate(1)
# Continue publishing messages until the ROS node is shut down
while not rospy.is_shutdown():
# Create a Twist message object to store linear and angular velocities
vel = Twist()
# Set linear and angular velocities for the turtle
vel.linear.x = 2.0
vel.angular.z = 1.0
# Log the velocities as an info-level log message
rospy.loginfo("Moving the turtle: linear_x = %s, angular_z = %s", vel.linear.x, vel.angular.z)
# Publish the velocities to the /turtle1/cmd_vel topic
pub.publish(vel)
# Sleep for the required time to maintain the desired message rate (1 message per second)
rate.sleep()
# Check if the script is being run as the main program and not being imported as a module
if __name__ == '__main__':
# Try to call the move_turtle function and start the publisher node
try:
move_turtle()
# Catch any ROSInterruptException that may occur (e.g., when the script is terminated using Ctrl+C)
except rospy.ROSInterruptException:
# Gracefully exit the script without displaying an error message
pass
- Save the file and close the text editor.
This script creates a node named move_turtle
that publishes a Twist
message to the /turtle1/cmd_vel
topic. The Twist
message contains two fields: linear
and angular
. Each field is a Vector3
message that contains three fields: x
, y
, and z
. In this example, we set the x
and z
fields of the linear
and angular
fields to 2.0 and 1.0, respectively. This means that the turtle will move forward at a linear velocity of 2.0 m/s and rotate at an angular velocity of 1.0 rad/s.
- run the script, make sure that the turtlesim is running, and then run the following command:
rosrun simple_pub_sub move_turtle.py
You should see the turtle moving forward and rotating in the turtlesim environment.
Congratulations! You've learned the basics of turtlesim and used it to explore ROS concepts such as topics, publishers, and subscribers. Turtlesim is a valuable tool for understanding how to work with real robots using ROS.
-
Navigate to the
scripts
directory of yoursimple_pub_sub package
,~/MorBot/morbot_ros/morbot_ws/src/simple_pub_sub/scripts
Create a new source file namedchange_color.py
inside thescripts
directory.cd ~/MorBot/morbot_ros/morbot_ws/src/simple_pub_sub/scripts touch change_color.py chmod +x change_color.py
-
Open the
change_color.py
file in a text editor, and paste the following code:
#!/usr/bin/env python
import rospy
from std_srvs.srv import Empty
def change_background_color(r, g, b):
rospy.init_node('change_background_color', anonymous=True)
# Set the background color parameters
rospy.set_param('/turtlesim/background_r', r)
rospy.set_param('/turtlesim/background_g', g)
rospy.set_param('/turtlesim/background_b', b)
# Wait for the clear service and call it
rospy.wait_for_service('clear')
try:
clear_background = rospy.ServiceProxy('clear', Empty)
clear_background()
except rospy.ServiceException as e:
print("Service call failed: %s"%e)
if __name__ == "__main__":
# Change the background color to red
change_background_color(255, 0, 0)
- Save the file and close the text editor.
This script creates a node named change_background_color
that changes the background color of the turtlesim environment to red. The background color is set using the /turtlesim/background_r
, /turtlesim/background_g
, and /turtlesim/background_b
parameters. The clear
service is then called to clear the turtlesim environment and display the new background color.
- Open new terminal windows and run the script, make sure that the turtlesim is running, and then run the following command:
Make sure turtlesim is running
rosrun simple_pub_sub change_color.py
The function change_background_color takes three arguments, each one representing the intensity of the Red, Green, and Blue channels respectively. The values can range from 0 to 255, where:
- 0 means the color is completely absent (no intensity),
- 255 means the color is fully present (highest intensity).
You should see the background color of the turtlesim environment change to red.
Utilizes a color sensor to detect the background color and moves the Turtlesim if the color matches the specified RGB values (red in this case).
The color of the path that the turtle draws is specified by path_color, and this color is ignored by the color sensor.
-
Navigate to the
scripts
directory of yoursimple_pub_sub package
,~/MorBot/morbot_ros/morbot_ws/src/simple_pub_sub/scripts
Create a new source file namedcolor_moving.py
inside thescripts
directory.cd ~/MorBot/morbot_ros/morbot_ws/src/simple_pub_sub/scripts touch color_moving.py chmod +x color_moving.py
-
Open the
color_moving.py
file in a text editor, and paste the following code:
#!/usr/bin/env python
import rospy
from geometry_msgs.msg import Twist
from turtlesim.msg import Color
# Global variable to hold the color detected by the turtle
color_detected = None
# Color of the path drawn by the turtle
path_color = Color(r=179, g=184, b=255)
# Callback for color sensor
def color_callback(color):
global color_detected
# Ignore if the color matches the path color
if color.r == path_color.r and color.g == path_color.g and color.b == path_color.b:
return
color_detected = color
# Function to move the turtle in a circle
def move_in_circle():
# global color_detected
# Create a publisher for the turtle velocity
publisher = rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size=10)
# Initialize the node
rospy.init_node('move_in_circle', anonymous=True)
# Create a subscriber for the color sensor
rospy.Subscriber('/turtle1/color_sensor', Color, color_callback)
print(color_detected)
# Set the rate
rate = rospy.Rate(1) # 1Hz
# Loop until shutdown
while not rospy.is_shutdown():
if color_detected is None:
continue
# Only move in circle if the color beneath the turtle is red
if color_detected.r == 255 and color_detected.g == 0 and color_detected.b == 0:
rospy.loginfo("MOVING")
# Create a Twist message and set linear.x and angular.z
twist = Twist()
twist.linear.x = 2.0 # Speed value
twist.angular.z = 2.0 # Turning rate
# Publish the Twist message
publisher.publish(twist)
rate.sleep()
if __name__ == '__main__':
try:
move_in_circle()
except rospy.ROSInterruptException:
pass
- Save the file and close the text editor.
This script creates a node named move_in_circle
that moves the turtle in a circle if the color beneath the turtle is red. The color sensor topic /turtle1/color_sensor
is subscribed to, and the callback function color_callback
is called whenever a message is received on the topic. The callback function stores the color detected by the turtle in the global variable color_detected
. The move_in_circle
function checks the value of color_detected
and moves the turtle in a circle if the color is red(in this demo).
- Open new terminal windows and run the script, make sure that the turtlesim is running, and then run the following command:
Make sure turtlesim is running
rosrun simple_pub_sub color_moving.py
You should see the turtle move in a circle if the color beneath it is red.
Now you can change the background color of the Turtlesim window , and use it to demonstrate sensory input control !!
-
Navigate to the
scripts
directory of yoursimple_pub_sub package
,~/MorBot/morbot_ros/morbot_ws/src/simple_pub_sub/scripts
Create a new source file namedspawn_turtle.py
inside thescripts
directory.cd ~/MorBot/morbot_ros/morbot_ws/src/simple_pub_sub/scripts touch spawn_turtle.py chmod +x spawn_turtle.py
-
Open the
spawn_turtle.py
file in a text editor, and paste the following code:
#!/usr/bin/env python
import rospy
from turtlesim.srv import Spawn
rospy.init_node('spawn_turtle')
rospy.wait_for_service('spawn')
spawn_service = rospy.ServiceProxy('spawn', Spawn)
# Spawn a new turtle at x=5, y=5, theta=0
spawn_service(5, 5, 0, "turtle2")
- Save the file and close the text editor.
Here's a brief explanation of the code and ROS service :
ROS Services:
In the Robot Operating System (ROS), services are a form of communication that allow one node to request a task from another node and receive a response.
This request-response communication model is useful for tasks that require a response, or when a task might take an unknown amount of time to complete.
Key Points:
-
Services are Synchronous: The requesting node (client) waits for the responding node (server) to complete the task before continuing.
-
Defined by .srv Files: Services in ROS are defined by .srv files that specify the structure of the request and response messages.
-
Service Commands in ROS: Use
rosservice list
to list services,rosservice info
to get details, androsservice call
to call a service.
Code:
rospy.init_node('spawn_turtle')
: Initializes a new ROS node called spawn_turtle
.
rospy.wait_for_service('spawn')
: Waits for the spawn
service to become available. This is a service provided by Turtlesim that allows us to spawn new turtles.
spawn_service = rospy.ServiceProxy('spawn', Spawn)
: Creates a service proxy for the spawn
service. This allows us to call the service using normal function call syntax.
spawn_service(5, 5, 0, "turtle2")
: Calls the spawn
service to spawn a new turtle at coordinates (5,5)
with an orientation of 0 and the name "turtle2"
.
NOW You can interact with each turtle separately using their unique topics
(e.g., turtle2/cmd_vel
for velocity commands)
- Open new terminal windows and run the script, make sure that the turtlesim is running, and then run the following command:
Make sure turtlesim is running
rosrun simple_pub_sub spawn_turtle.py
- If everything works correctly, a second turtle named "turtle2" should appear in the Turtlesim window at the coordinates (5,5) !
Monitor the new turtle's position
To see the new turtle's position in real-time, subscribe to the /turtle2/pose
topic using the rostopic echo
command:
rostopic echo /turtle2/pose
You can interact with each turtle you spawn separately using their unique topics
and names
(e.g., turtle1/cmd_vel
,turtle2/cmd_vel
,turtle3/cmd_vel
)
Enjoy exploring with multiple Turtlesims in ROS!
- Set up the Jetson Nano And Linux.