Ros2 Cartographer Setup(2)_custom serial communication node

mseokq23·2024년 11월 18일
post-thumbnail

Developing Self Driving with Jetson Nano · Phase 0 · ROS2 Foxy (archived) · ROS2 Setup (3)

Goal: A custom ROS2 node that sends motor commands from a topic to the ESP32 over USB serial.
Result: ❌ Failed / abandoned — the node worked after the port fix in the next post, but ROS2 was dropped; the same idea became motor_control_node.py in Jetson Project #9.
Final code: jetson-nano-final-code → src/motor_control/scripts/motor_control_node.py (ROS1 version of this idea)
Env: Jetson Nano B01 · Ubuntu 20.04 · ROS2 Foxy

To talk to the ESP32 over USB serial, I wrote a custom ROS2 node.
My first plan was git clone https://github.com/ros-drivers/ros2_serial_example.git, but that package isn't supported anymore, so I made my own node.

What the node does

  • Sends commands to the ESP32 to control the motors
  • Reads data from the ESP32 when needed

1. Create the package

Step 1. Go to the workspace

cd ~/ros2_ws/src

Step 2. Create a new ROS2 package

ros2 pkg create --build-type ament_python serial_communication

Step 3. Check the package folder

cd ~/ros2_ws/src/serial_communication/serial_communication
ls

The folder is empty or contains only __init__.py.

2. Write the node

Step 4. Create serial_node.py

nano ~/ros2_ws/src/serial_communication/serial_communication/serial_node.py

💡 The original post used sudo nano. sudo is not needed for files in your home folder; files created with sudo belong to root and need sudo again for every edit.

⚠️ Updated later: the port /dev/ttyUSB1 is wrong — the ESP32 is /dev/ttyACM0 (next post). Final ROS1 version: src/motor_control/scripts/motor_control_node.py.

📄 ~/ros2_ws/src/serial_communication/serial_communication/serial_node.py

#!/usr/bin/env python3

import rclpy
from rclpy.node import Node
import serial
from std_msgs.msg import String

class SerialCommunicationNode(Node):
    def __init__(self):
        super().__init__('serial_communication_node')

        # serial port edit
        self.serial_port = '/dev/ttyUSB1' #This port should be changed to real port number  
        self.baud_rate = 115200           

        # port open
        try:
            self.ser = serial.Serial(self.serial_port, self.baud_rate, timeout=1)
            self.get_logger().info(f'Serial port {self.serial_port} opened at {self.baud_rate} baud.')
        except serial.SerialException as e:
            self.get_logger().error(f'Failed to open serial port: {e}')
            exit(1)

        # timer edit for reading data periodically
        self.timer = self.create_timer(0.1, self.read_from_serial)

        # Subscribe to Ros2 topics to receive motor control commands
        self.subscription = self.create_subscription(
            String,
            'motor_commands',
            self.write_to_serial,
            10)
        self.subscription  # prevent unused variable warning

    def read_from_serial(self):
        if self.ser.in_waiting > 0:
            data = self.ser.readline().decode('utf-8').rstrip()
            self.get_logger().info(f'Received from ESP32: {data}')
            # Data can be published as ROS2 topic if necessary

    def write_to_serial(self, msg):
        command = msg.data + '\n'
        self.ser.write(command.encode('utf-8'))
        self.get_logger().info(f'Sent to ESP32: {msg.data}')

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

if __name__ == '__main__':
    main()

Make it executable:

chmod +x ~/ros2_ws/src/serial_communication/serial_communication/serial_node.py

3. Package settings

Step 5. Edit setup.py

Add the dependency and the entry point so the node can be started with ros2 run:

nano ~/ros2_ws/src/serial_communication/setup.py

📄 ~/ros2_ws/src/serial_communication/setup.py

from setuptools import setup

package_name = 'serial_communication'

setup(
    name=package_name,
    version='0.0.0',
    packages=[package_name],
    py_modules=[],
    data_files=[
        ('share/ament_index/resource_index/packages',
            ['resource/' + package_name]),
        ('share/' + package_name, ['package.xml']),
    ],
    install_requires=['setuptools', 'pyserial'],
    zip_safe=True,
    maintainer='mseokq23',
    maintainer_email='minseok1270@gmail.com',
    description='Serial communication node for ROS2',
    license='Apache License 2.0',
    tests_require=['pytest'],
    entry_points={
        'console_scripts': [
            'serial_node = serial_communication.serial_node:main',
        ],
    },
)

  • pyserial added to install_requires
  • entry point serial_node = serial_communication.serial_node:main

Step 6. Edit package.xml

cd ~/ros2_ws/src/serial_communication
ls
nano package.xml

or directly:

nano ~/ros2_ws/src/serial_communication/package.xml

📄 ~/ros2_ws/src/serial_communication/package.xml

<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
  <name>serial_communication</name>
  <version>0.0.0</version>
  <description>Custom serial communication node using PySerial</description>
  <maintainer email="minseok1270@gmail.com">mseokq23</maintainer>
  <license>Apache License 2.0</license>

  <test_depend>ament_copyright</test_depend>
  <test_depend>ament_flake8</test_depend>
  <test_depend>ament_pep257</test_depend>
  <test_depend>python3-pytest</test_depend>

  <exec_depend>rclpy</exec_depend>
  <exec_depend>std_msgs</exec_depend>
  <exec_depend>pyserial</exec_depend>

  <export>
    <build_type>ament_python</build_type>
  </export>
</package>

💡 The second line was cut off in nano (... schematyp>); above is the complete line.
💡 For rosdep install, the serial library's key is python3-serial (there is no pyserial key). The build itself does not need it.

Added the dependencies rclpy, std_msgs, pyserial.

4. Build and test

Step 7. Build the package

cd ~/ros2_ws
colcon build --packages-select serial_communication

Source the workspace (or simply close the terminal and open a new one):

source install/setup.bash

Step 8. Run the node

Connect the ESP32 to the Jetson Nano with a USB cable, then:

ros2 run serial_communication serial_node

Without a connected ESP32 the node fails like this (the port cannot be opened).

To use the serial port without sudo, add your user to the dialout group and reboot:

sudo usermod -a -G dialout $USER

5. ESP32 test sketch

The ESP32 reads one line per command at the same baud rate (115200) and answers with Received: <command>.

⚠️ Bug in the original sketch: the } that closes setup() was inside the comment (// same Jetson Nano board rate}), so the sketch does not compile. Fixed below. The firmware used later is in Jetson Project #9; final version: firmware/esp32_motor_control/esp32_motor_control.ino.

📄 ESP32 sketch (Arduino IDE)

void setup() {
  Serial.begin(115200); // same baud rate as the Jetson Nano node
}

void loop() {
  if (Serial.available() > 0) {
    String command = Serial.readStringUntil('\n');
    Serial.println("Received: " + command);
    // add motor control logic
    if (command == "forward") {
      // drive the motors forward here
    } else if (command == "backward") {
      // drive the motors backward here
    }
    // add more movements if needed
  }
}

➡️ Next: Ros2 Cartographer Setup(2)_custom serial communication node_trouble shooting

0개의 댓글