ROS2极简入门(二)创建发布节点和接收节点

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值