🧠Talking Bots!

gayatri kumargayatri kumar
6 min read

πŸ“ Welcome back to Robot Town!

We’ve built homes (packages) for our robots, and we gave them basic functions. But so far, our robots have been silent.
It’s time they got a voice!
In today’s adventure, we’ll install the walkie-talkie system in our robot homes.


πŸ—¨οΈ What is a Node?

Think of a Node as a robot’s communication center β€” like a walkie-talkie that lets it say things (and later, listen too).

In ROS2:

  • A node is a unit of execution.

  • It’s a Python program that runs inside a package.

  • It has a name (like chatter_bot) and it can publish, subscribe, and more.

  • Today we only focus on talking, not listening.


πŸ—οΈ Project Setup: Let’s Build the Gossip System

πŸ’¬ Objective:

We will make one robot named ChatterBot who keeps saying something every second β€” just like a town gossip.


🧱 Step 1: Create a New Package for ChatterBot

Navigate to your workspace:

cd ~/robot_town_ws/src

Create a new ROS2 Python package:

ros2 pkg create --build-type ament_python chatter_bot --dependencies rclpy

This creates:

robot_town_ws/
└── src/
    └── chatter_bot/         ← New package
        β”œβ”€β”€ chatter_bot/     ← Python module folder
        β”‚   └── __init__.py
        β”œβ”€β”€ package.xml
        └── setup.py

πŸ“¦ Why two chatter_bot folders?
The outer one is the package.
The inner one is the Python module where our code lives.
Think of the outer one as the house and the inner one as the rooms inside.


πŸ“ Step 2: Write the Gossip Node

Create a new file inside the inner chatter_bot/ folder:

touch ~/robot_town_ws/src/chatter_bot/chatter_bot/gossip.py

Paste this code:

import rclpy
from rclpy.node import Node

# πŸ—£οΈ ChatterBot is a friendly node that keeps talking every second,
# counting up its "gossip" messages like a lively townsperson.
class ChatterBot(Node):
    def __init__(self):
        # Initialize the node with the name 'chatter_bot'
        super().__init__('chatter_bot')

        # Initialize a counter to keep track of how many times we've gossiped
        self.counter = 0

        # πŸ•’ Create a timer that triggers the gossip method every 1 second
        # create_timer(interval_sec, callback) sets up a periodic callback
        self.timer = self.create_timer(1.0, self.gossip)

    def gossip(self):
        # πŸ“ Use the node's built-in logger to print an informational message

        # get_logger() provides the logger interface for this node
        # info() logs a message at the "info" severity level,
        # which is typically shown on the console by default
        logger = self.get_logger().info(f"ChatterBot says: Gossip number {self.counter}")

        # Increment the counter for the next gossip message
        self.counter += 1

# 🏁 Program entry point
def main(args=None):
    # Initialize ROS2 communication for this Python program
    rclpy.init(args=args)

    # Create an instance of ChatterBot
    node = ChatterBot()

    # Keep the node alive, listening and processing callbacks like timers
    rclpy.spin(node)

    # Clean up after the node is stopped
    node.destroy_node()
    rclpy.shutdown()

# Only run main() if this script is executed directly (not imported)
if __name__ == '__main__':
    main()

🧠 Code Breakdown (Plain English)

Code LineMeaning
class ChatterBot(Node)We are creating a robot with communication powers.
create_timer(1.0, self.gossip)This schedules the robot to speak every 1 second.
self.get_logger().info(...)This prints to the terminal β€” like a robot speaking out loud.
rclpy.spin()Keeps the node alive forever β€” like switching the bot β€œon”.

πŸŽ™οΈ Think of the gossip() function as your robot speaking into a walkie-talkie.


βš™οΈ Step 3: Add an Entry Point

Open your setup.py file and edit the entry_points section:

entry_points={
    'console_scripts': [
        'gossip = chatter_bot.gossip:main',
    ],
},

Now ROS2 knows that when you run gossip, it should run the main() in gossip.py.


πŸ”¨ Step 4: Build the Package

Navigate to the root of your workspace:

cd ~/robot_town_ws
colcon build

πŸ§ͺ Step 5: Source and Run

Every time you open a new terminal, you need to run:

source install/setup.bash

This sets up the entry points and environment for ROS2.

Then run your robot:

ros2 run chatter_bot gossip

You should see output like:

[INFO] [chatter_bot]: ChatterBot says: Gossip number 0
[INFO] [chatter_bot]: ChatterBot says: Gossip number 1
[INFO] [chatter_bot]: ChatterBot says: Gossip number 2
...

πŸŽ‰ Congratulations! Your robot is officially TALKING!


🧭 Folder Recap

robot_town_ws/
β”œβ”€β”€ src/
β”‚   └── chatter_bot/
β”‚       β”œβ”€β”€ chatter_bot/
β”‚       β”‚   └── gossip.py      ← Our talking bot
β”‚       β”œβ”€β”€ setup.py
β”‚       β”œβ”€β”€ package.xml
β”‚       └── ...
└── install/
    └── ... (generated after build)

πŸ—οΈ Building the Second House: GreeterBot

We’ll keep our previous packages:

  • mayor_bot: The robot mayor from Article 1

  • door_bot: The door-opening bot from Article 2

  • chatter_bot: Our talkative friend from Part 1

Let’s now add a fourth house:

cd ~/robot_town_ws/src
ros2 pkg create --build-type ament_python greeter_bot --dependencies rclpy

Your updated workspace structure:

robot_town_ws/
└── src/
    β”œβ”€β”€ mayor_bot/
    β”œβ”€β”€ door_bot/
    β”œβ”€β”€ chatter_bot/
    β”‚   └── chatter_bot/
    β”‚       └── gossip.py
    └── greeter_bot/
        └── greeter_bot/

πŸ“ Create the GreeterBot Node

Let’s give greeter_bot a voice!

Create a file:

touch ~/robot_town_ws/src/greeter_bot/greeter_bot/greet.py

Add this code:

import rclpy
from rclpy.node import Node

class GreeterBot(Node):
    def __init__(self):
        super().__init__('greeter_bot')
        self.timer = self.create_timer(2.0, self.say_hi)  # Speak every 2 seconds

    def say_hi(self):
        self.get_logger().info("GreeterBot waves: Welcome to Robot Town!")

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

if __name__ == '__main__':
    main()

πŸ”— Add Entry Point in setup.py

In greeter_bot/setup.py, update the entry points:

entry_points={
    'console_scripts': [
        'greet = greeter_bot.greet:main',
    ],
},

This tells ROS2: β€œHey, when someone runs ros2 run greeter_bot greet, launch the greet.py file!”


πŸ”¨ Rebuild Everything

You’ve added a new package. Time to build the entire town again:

cd ~/robot_town_ws
colcon build

After the build completes:

source install/setup.bash

πŸ§ͺ Run Both Bots Together

Open two terminals, and in each:

  1. Source the workspace:
cd ~/robot_town_ws
source install/setup.bash
  1. In terminal 1:
ros2 run chatter_bot gossip
  1. In terminal 2:
ros2 run greeter_bot greet

You should now see:

[INFO] [chatter_bot]: ChatterBot says: β€œI heard DoorBot opened again!”
[INFO] [chatter_bot]: ChatterBot says: β€œMayorBot tripped on his welcome mat!”
[INFO] [greeter_bot]: GreeterBot waves: Welcome to Robot Town!
[INFO] [chatter_bot]: ChatterBot says: β€œDoorBot and GreeterBot are up to something.”
...

πŸŽ‰ Success! Two bots in different homes, speaking independently!


🧠 What Did We Just Learn?

ConceptWhat It Means
PackageA robot’s home β€” contains its code
NodeA communication unit β€” like a walkie-talkie
Entry pointA shortcut command to run a Python script
Multiple NodesEach bot is its own process β€” can speak in parallel
TimerAllows repeating actions at a fixed interval

🏘️ Final Workspace Recap

robot_town_ws/
└── src/
    β”œβ”€β”€ mayor_bot/
    β”‚   └── mayor_bot/
    β”‚       └── greet.py
    β”œβ”€β”€ door_bot/
    β”‚   └── door_bot/
    β”‚       └── open.py
    β”œβ”€β”€ chatter_bot/
    β”‚   └── chatter_bot/
    β”‚       └── gossip.py
    └── greeter_bot/
        └── greeter_bot/
            └── greet.py

πŸš€ Each of these packages has a bot with its own role in the town.


πŸŽ™οΈ Up Next: The Town Radio System (Topics & Publishing)

Imagine the town square filled with lively announcements that everyone can hear! In this next article, we'll set up our own public radio frequency using ROS2 Topics and Publishing.
Meet WeatherBot, your friendly weather announcer, broadcasting temperature updates every few seconds. Get ready to bring Robot Town’s news to life! πŸŒ€οΈπŸ“‘

But before we dive into that, it’s worth pausing and letting the idea of independent talkative nodes sink in.

10
Subscribe to my newsletter

Read articles from gayatri kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

gayatri kumar
gayatri kumar