ROS2极简入门(二)
在上一章里面我们介绍了如何创建一个节点,这次我们编写一个通信机制.
文章目录
一、创建工作空间
创建工作空间就是新建文件夹
mkdir -p my_test01/src
cd my_test01/src
二、创建自己的包
2.1 ros2 pkg create命令
代码如下(示例):
ros2 pkg create test_publish --build-type ament_cmake --node-name my_publish --dependencies std_msgs rclcpp
2.2 进入vs
直接在该目录下的命令行中输入
code .
不要忘记符号"."
2.3 创建发布节点
在vs中打开my_pubilsh.cpp
复制代码:
#include <chrono>
#include <functional>
#include <memory>
#include <string>
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"
using namespace std::chrono_literals;
/* This example creates a subclass of Node and uses std::bind() to register a* member function as a callback from the timer. */
class MinimalPublisher : public rclcpp::Node{
public:
MinimalPublisher()
: Node("minimal_publisher"), count_(0)
{
publisher_ = this->create_publisher<std_msgs::msg::String>("topic", 10);
timer_ = this->create_wall_timer(
500ms, std::bind(&MinimalPublisher::timer_callback, this));
}
private:
void timer_callback()
{
auto message = std_msgs::msg::String();
message.data = "Hello, world! " + std::to_string(count_++);
RCLCPP_INFO(this->get_logger(), "Publishing: '%s'", message.data.c_str());
publisher_->publish(message);
}
rclcpp::TimerBase::SharedPtr timer_;
rclcpp::Publisher<std_msgs::msg::String>::SharedPtr publisher_;
size_t count_;
};
int main(int argc, char * argv[])
{
rclcpp::init(argc, argv);
rclcpp::spin(std::make_shared<MinimalPublisher>());
rclcpp::shutdown();
return 0;
}
2.4 colcon build
在my_test01目录下利用利用命令行编译
~/my_test01$ colcon build
三 source环境
在/my_test01下
source install/setup.bash
四 运行功能包中的节点
在终端中使用如下命令即可运行新建功能包的节点啦:
ros2 run test_publish my_publish
五 总结
主要介绍了如何进行发布话题
六 扩展
提供接收节点代码,创建接收节点
#include
#include “rclcpp/rclcpp.hpp”
#include “std_msgs/msg/string.hpp”
using std::placeholders::_1;
class MinimalSubscriber : public rclcpp::Node{
public:
MinimalSubscriber()
: Node(“minimal_subscriber”)
{
subscription_ = this->create_subscription<std_msgs::msg::String>(
“topic”, 10, std::bind(&MinimalSubscriber::topic_callback, this, _1));
}
private:
void topic_callback(const std_msgs::msg::String::SharedPtr msg) const
{
RCLCPP_INFO(this->get_logger(), “I heard: ‘%s’”, msg->data.c_str());
}
rclcpp::Subscription<std_msgs::msg::String>::SharedPtr subscription_;};
int main(int argc, char * argv[])
{
rclcpp::init(argc, argv);
rclcpp::spin(std::make_shared());
rclcpp::shutdown();
return 0;
}