Ros turtlesim - arieldo/MorBot GitHub Wiki

Getting Started with turtlesim in ROS

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Start turtlesim
  4. Control the turtle using the turtle_teleop_key node
  5. Explore ROS topics in turtlesim
  6. Monitor the turtle's position
  7. Control the turtle programmatically
  8. Changing the Background Color of Turtlesim
  9. Moving the Turtlesim Based on Background Color
  10. Spawning a multiple Turtle in Turtlesim Window

Introduction:

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.

Prerequisites:

  • 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

Step 1: start turtlesim

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.

Step 2: Control the turtle using the turtle_teleop_key node

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.

Step 3: Explore ROS topics in turtlesim

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.

Step 4: Monitor the turtle's position

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.

Step 5: Control the turtle programmatically

  1. Navigate to the scripts directory of your simple_pub_sub package, ~/MorBot/morbot_ros/morbot_ws/src/simple_pub_sub/scripts Create a new source file named move_turtle.py inside the scripts directory.

    cd ~/MorBot/morbot_ros/morbot_ws/src/simple_pub_sub/scripts
    touch move_turtle.py
    chmod +x move_turtle.py
  2. 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
  1. 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.

  1. 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.

Changing the Background Color of Turtlesim

  1. Navigate to the scripts directory of your simple_pub_sub package, ~/MorBot/morbot_ros/morbot_ws/src/simple_pub_sub/scripts Create a new source file named change_color.py inside the scripts directory.

    cd ~/MorBot/morbot_ros/morbot_ws/src/simple_pub_sub/scripts
    touch change_color.py
    chmod +x change_color.py
  2. 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)
  1. 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.

  1. 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.

Moving the Turtlesim Based on Background Color

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.

  1. Navigate to the scripts directory of your simple_pub_sub package, ~/MorBot/morbot_ros/morbot_ws/src/simple_pub_sub/scripts Create a new source file named color_moving.py inside the scripts directory.

    cd ~/MorBot/morbot_ros/morbot_ws/src/simple_pub_sub/scripts
    touch color_moving.py
    chmod +x color_moving.py
  2. 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
  1. 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).

  1. 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 !!

Spawning multiple Turtles in Turtlesim Window

  1. Navigate to the scripts directory of your simple_pub_sub package, ~/MorBot/morbot_ros/morbot_ws/src/simple_pub_sub/scripts Create a new source file named spawn_turtle.py inside the scripts directory.

    cd ~/MorBot/morbot_ros/morbot_ws/src/simple_pub_sub/scripts
    touch spawn_turtle.py
    chmod +x spawn_turtle.py
  2. 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")
  1. 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:

  1. Services are Synchronous: The requesting node (client) waits for the responding node (server) to complete the task before continuing.

  2. Defined by .srv Files: Services in ROS are defined by .srv files that specify the structure of the request and response messages.

  3. Service Commands in ROS: Use rosservice list to list services, rosservice info to get details, and rosservice 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)

  1. 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!

Next

⚠️ **GitHub.com Fallback** ⚠️