Nodes - dhanushshettigar/Getting-Started-With-ROS2 GitHub Wiki

ROS 2 Nodes

What is a Node?

In ROS 2, a Node is a basic unit of computation. A node is responsible for a single task within a system, such as reading sensor data, controlling motors, or managing a user interface. ROS 2 nodes communicate with each other to create a distributed and modular system.

Nodes can:

  • Publish data to topics (e.g., sensor readings).
  • Subscribe to topics to receive data (e.g., motor commands).
  • Provide services for requests (e.g., turning on a light).
  • Use services to make requests (e.g., asking for robot status).

Why Use Nodes?

Using nodes makes your robotic system:

  • Modular: Tasks are split into different nodes, making the system easier to manage.
  • Scalable: Nodes can run on multiple machines, enabling distributed computing.
  • Reusable: Nodes can be reused in different systems or updated individually without affecting the entire system.

Creating a Simple Node in Python

1. Create a Package

First, create a new ROS 2 package for your node (assuming your workspace is already set up):

cd /ros2_ws/src
ros2 pkg create first_node --build-type ament_python --dependencies rclpy

This command will create a package named first_node

2. Create the Python Node Script

Next, navigate to the package folder and create a Python file for your node:

cd /ros2_ws/src/first_node/first_node
sudo nano my_node.py

3. Write the Node Code

import rclpy
from rclpy.node import Node

class MyNode(Node):
    def __init__(self):
        super().__init__('my_node')
        self.get_logger().info('Hello, ROS 2 Node!')

def main(args=None):
    rclpy.init(args=args)
    node = MyNode()
    rclpy.spin(node)
    rclpy.shutdown()

if __name__ == '__main__':
    main()

This simple node will log a message, "Hello, ROS 2 Node!", when executed.

4. Modify Setup.py

Open setup.py file.

cd ..
sudo nano setup.py

Add the following line within the console_scripts brackets of the entry_points field:

entry_points={
        'console_scripts': [
                'my_node = first_node.my_node:main',
        ],
},

Don’t forget to save.

5. Build the Package

Return to the root of your workspace and build the new package:

cd ../..
colcon build

6. Source the Workspace

After building, don't forget to source the workspace again:

source install/setup.bash

7. Run the Node

Finally, run the node using the ros2 run command:

ros2 run first_node my_node

You should see the message "Hello, ROS 2 Node!" in the terminal.

Conclusion

Nodes are the building blocks of any ROS 2 system. By creating and running nodes, you can build modular, scalable, and reusable components in your robotic application.