ros launch实现小车移动

上一章说明了如何用命令行实现小车移动,这章实现如何编写launch文件来使小车移动和通过键盘来时小车移动。

编写c++代码文件

首先要编写关于发布速度命令的c++代码文件,要在包中的src下来编写这个文件。

我是在turn_on_dlrobot_robot底盘驱动的包中的src文件夹中编写关于发布速度节点的c++代码文件(也可以重新建立一个功能包,这个包功能就是专门来发布速度节点,这个后面章节会说明,也很简单),这边我命名为forward_move_node.cpp

这是我的一个forwrd_move_node.cpp源码,仅供参考

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include "rclcpp/rclcpp.hpp"
#include "geometry_msgs/msg/twist.hpp"
#include <chrono>

using namespace std::chrono_literals;

class ForwardMoveNode : public rclcpp::Node
{
public:
ForwardMoveNode() : Node("forward_move_node")
{
// 创建发布者,发布到 /cmd_vel 话题
publisher_ = this->create_publisher<geometry_msgs::msg::Twist>("cmd_vel", 10);

// 创建定时器,每100ms发布一次速度指令
timer_ = this->create_wall_timer(100ms, std::bind(&ForwardMoveNode::publish_velocity, this));

RCLCPP_INFO(this->get_logger(), "Forward move node started - moving at 0.05 m/s");
}

private:
void publish_velocity()
{
// 创建速度消息
auto msg = geometry_msgs::msg::Twist();

// 设置线速度:x方向0.05 m/s(向前),y和z方向为0
msg.linear.x = 0.05;
msg.linear.y = 0.0;
msg.linear.z = 0.0;

// 设置角速度:所有方向都为0(无转动)
msg.angular.x = 0.0;
msg.angular.y = 0.0;
msg.angular.z = 0.0;

// 发布消息
publisher_->publish(msg);
RCLCPP_DEBUG(this->get_logger(), "Published velocity: linear.x=0.05, angular.z=0.0");
}

rclcpp::Publisher<geometry_msgs::msg::Twist>::SharedPtr publisher_;
rclcpp::TimerBase::SharedPtr timer_;
};

int main(int argc, char * argv[])
{
rclcpp::init(argc, argv);

// 创建节点
auto node = std::make_shared<ForwardMoveNode>();

try {
// 运行节点
rclcpp::spin(node);
} catch (const std::exception& e) {
RCLCPP_ERROR(node->get_logger(), "Exception in forward move node: %s", e.what());
}

// 清理
rclcpp::shutdown();
return 0;
}

修改CMakeLists.txt文件

要在CMakeLists.txt中添加这几句语句,在实践(二)中有具体说明。

编写launch文件

在launch文件夹中,编写launch.py代码文件,来启动我们编写的c++速度节点。我命名为forward_move_launch.py文件

让小车动起来

首先先进行编译,在工作空间根目录编译

1
colcon build

然后在命令框中进行ros环境配置

1
source install/setup.sh

打开小车底盘驱动通信,实践(四)有说明
再打开一个命令框,输入

1
ros2 launch turn_on_dlrobot_robot(包名) forward_move.launch.py(launch文件名)

即可启动成功。

通过键盘来使小车移动

这个很简单,有一个ros2的官方包,支持用键盘来控制小车移动,teleop_twist_keyboard包,可以去搜索一下安装。

安装后,首先还是打开小车底盘驱动通信

然后输入指令

1
ros2 run teleop_twist_keyboard teleop_twist_keyboard

就可以通过键盘来控制指令