Writing - A - Simple - Publisher - and - Subscriber in C++
Writing - A - Simple - Publisher - and - Subscriber in C++
cd ~/ros2_ws/src
ros2 pkg create --build-type ament_cmake cpp_pubsub
#include <chrono>
#include <functional>
#include <memory>
#include <string>
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"
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_;
};
rclcpp/rclcpp.hppinclude which allows you to use the most common pieces of the ROS
2 system. Last is std_msgs/msg/string.hpp , which includes the built-in message type you
will use to publish data.
Every this in the code is referring to the node.
#include <memory>
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"
using std::placeholders::_1;
Now the node is named minimal_subscriber , and the constructor uses the
node’s create_subscription class to execute the callback.
Editing CMakelists
Below the existing dependency find_package(ament_cmake REQUIRED) , add the lines:
find_package(rclcpp REQUIRED)
find_package(std_msgs REQUIRED)
add the executable and name it talker so you can run your node using ros2 run :
add_executable(talker src/publisher_member_function.cpp)
ament_target_dependencies(talker rclcpp std_msgs)
add_executable(listener src/subscriber_member_function.cpp)
ament_target_dependencies(listener rclcpp std_msgs)
add the install(TARGETS...) section so ros2 run can find your executable:
cmake_minimum_required(VERSION 3.5)
project(cpp_pubsub)
# Default to C++14
if(NOT CMAKE_CXX_STANDARD)
set(CMAKE_CXX_STANDARD 14)
endif()
find_package(ament_cmake REQUIRED)
find_package(rclcpp REQUIRED)
find_package(std_msgs REQUIRED)
add_executable(talker src/publisher_member_function.cpp)
ament_target_dependencies(talker rclcpp std_msgs)
add_executable(listener src/subscriber_member_function.cpp)
ament_target_dependencies(listener rclcpp std_msgs)
install(TARGETS
talker
listener
DESTINATION lib/${PROJECT_NAME})
ament_package()
build:
source:
. install/setup.bash
run: