ROS 2 Basics
An introduction to the Robot Operating System 2 (ROS 2) — the middleware framework used across all e-Yantra projects.
TIP
New to ROS 2? Follow the steps below in order. Once you're comfortable, explore Path Planning and Control Systems.
Core Concepts
| Concept | Description |
|---|---|
| Node | A single-purpose executable process |
| Topic | Named bus for asynchronous message passing |
| Service | Synchronous request/response communication |
| Action | Long-running tasks with feedback |
| Package | Organizational unit of ROS 2 code |
Creating Your First Node
python
import rclpy
from rclpy.node import Node
from std_msgs.msg import String
class MinimalPublisher(Node):
def __init__(self):
super().__init__('minimal_publisher')
self.publisher_ = self.create_publisher(String, 'topic', 10)
self.timer = self.create_timer(0.5, self.timer_callback)
def timer_callback(self):
msg = String()
msg.data = 'Hello from e-Yantra!'
self.publisher_.publish(msg)
self.get_logger().info(f'Publishing: "{msg.data}"')
def main(args=None):
rclpy.init(args=args)
rclpy.spin(MinimalPublisher())
rclpy.shutdown()python
import rclpy
from rclpy.node import Node
from std_msgs.msg import String
class MinimalSubscriber(Node):
def __init__(self):
super().__init__('minimal_subscriber')
self.create_subscription(String, 'topic', self.callback, 10)
def callback(self, msg):
self.get_logger().info(f'Received: "{msg.data}"')
def main(args=None):
rclpy.init(args=args)
rclpy.spin(MinimalSubscriber())
rclpy.shutdown()Useful CLI Commands
bash
# List all running nodes
ros2 node list
# List all active topics
ros2 topic list
# Echo a topic in real time
ros2 topic echo /topic_name
# Check message type
ros2 topic info /topic_name
# Run a node
ros2 run <package_name> <executable_name>
# Launch a launch file
ros2 launch <package_name> <launch_file>.pyBuilding a Package
bash
# Create a new package
ros2 pkg create --build-type ament_python my_package
# Build workspace
colcon build --symlink-install
# Source the workspace
source install/setup.bash