1. 编译工具安装
sudo apt update
sudo apt install python3-catkin-pkg python3-rosdep python3-rosinstall-generator python3-wstool python3-rosinstall build-essential
sudo rosdep init
rosdep update

2. 构建节点
mkdir -p ~/ros2_ws/src
cd ~/ros2_ws
ros2 pkg create turtlebot_suo --build-type ament_python --dependencies rclpy sensor_msgs geometry_msgstouch turtlebot_suo/turtlebot_suo/ob_avoid.py
chmod +x turtlebot_suo/turtlebot_suo/ob_avoid.py
entry_points={'console_scripts': ['ob_avoid = turtlebot_suo.ob_avoid:main',],},
cd ~/ros2_ws
colcon build --packages-select turtlebot_suo
source install/setup.bash

3. 避障程序
import rclpy
from rclpy.node import Node
from sensor_msgs.msg import LaserScan
from geometry_msgs.msg import Twistclass ObstacleAvoidance(Node):def __init__(self):super().__init__('ob_avoid')self.publisher_ = self.create_publisher(Twist, 'cmd_vel', 10)self.subscription_ = self.create_subscription(LaserScan,'scan',self.laser_scan_callback,10)self.subscription_ def laser_scan_callback(self, msg):front_range = msg.ranges[0:45] + msg.ranges[-45:]min_distance = min(front_range)cmd_msg = Twist()if min_distance < 0.5:cmd_msg.angular.z = 0.5self.get_logger().info('# 障碍物距离小于0.5米,左转.')else:cmd_msg.linear.x = 0.2self.publisher_.publish(cmd_msg)def main(args=None):rclpy.init(args=args)node = ObstacleAvoidance()try:rclpy.spin(node)except KeyboardInterrupt:passfinally:node.destroy_node()rclpy.shutdown()if __name__ == '__main__':main()
4. 效果
roslaunch turtlebot3_gazebo turtlebot3_world.launch
ros2 run turtlebot_suo ob_avoid


