Home » ROS2与C++入门教程 » ROS2与C++入门教程-创建ros2接口

ROS2与C++入门教程-创建ros2接口

ROS2与C++入门教程-创建ros2接口

说明:

  • 介绍如何创建ros2接口
  • 本文以创建一个msg类型的接口为例

步骤:

  • 创建一个新包
cd ~/dev_ws/src
ros2 pkg create --build-type ament_cmake more_interfaces
  • 创建msg目录
mkdir more_interfaces/msg
vim AddressBook.msg
  • 内容如下:
bool FEMALE=true
bool MALE=false

string first_name
string last_name
bool gender
uint8 age
string address
  • 在package.xml里增加
<buildtool_depend>rosidl_default_generators</buildtool_depend>

<exec_depend>rosidl_default_runtime</exec_depend>

<member_of_group>rosidl_interface_packages</member_of_group>
  • 在CMakeLists.txt增加
find_package(rosidl_default_generators REQUIRED)

set(msg_files
  "msg/AddressBook.msg"
)

rosidl_generate_interfaces(${PROJECT_NAME}
  ${msg_files}
)

ament_export_dependencies(rosidl_default_runtime)
  • 在src目录下,新建publish_address_book.cpp
vim publish_address_book.cpp
  • 内容如下:
#include <chrono>
#include <memory>

#include "rclcpp/rclcpp.hpp"
#include "more_interfaces/msg/address_book.hpp"

using namespace std::chrono_literals;

class AddressBookPublisher : public rclcpp::Node
{
public:
  AddressBookPublisher()
  : Node("address_book_publisher")
  {
    address_book_publisher_ =
      this->create_publisher<more_interfaces::msg::AddressBook>("address_book", 10);

    auto publish_msg = [this]() -> void {
        auto message = more_interfaces::msg::AddressBook();

        message.first_name = "John";
        message.last_name = "Doe";
        message.age = 30;
        message.gender = message.MALE;
        message.address = "unknown";

        std::cout << "Publishing Contact\nFirst:" << message.first_name <<
          "  Last:" << message.last_name << std::endl;

        this->address_book_publisher_->publish(message);
      };
    timer_ = this->create_wall_timer(1s, publish_msg);
  }

private:
  rclcpp::Publisher<more_interfaces::msg::AddressBook>::SharedPtr address_book_publisher_;
  rclcpp::TimerBase::SharedPtr timer_;
};


int main(int argc, char * argv[])
{
  rclcpp::init(argc, argv);
  rclcpp::spin(std::make_shared<AddressBookPublisher>());
  rclcpp::shutdown();

  return 0;
}
  • 修改CMakelist.txt 增加如下内容:
find_package(rclcpp REQUIRED)

add_executable(publish_address_book
  src/publish_address_book.cpp
)

ament_target_dependencies(publish_address_book
  "rclcpp"
)

install(TARGETS publish_address_book
 DESTINATION lib/${PROJECT_NAME})


rosidl_target_interfaces(publish_address_book
  ${PROJECT_NAME} "rosidl_typesupport_cpp")
  • 编译包
cd ~/dev_ws
colcon build --packages-up-to more_interfaces
  • 测试
. install/local_setup.bash
ros2 run more_interfaces publish_address_book
  • 新开终端
. install/local_setup.bash
ros2 topic echo /address_book

纠错,疑问,交流: 请进入讨论区点击加入Q群

获取最新文章: 扫一扫右上角的二维码加入“创客智造”公众号


标签: ROS2与C++入门教程