1、publisher
节点名 auto node = rclcpp::Node::make_shared(“publisher”);
消息类型和话题 auto pub = node->create_publisher<std_msgs::msg::String>(“/pub_sub”, 10);
发送消息 pub->publish(myMessage); //注意用->
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"
using namespace std::chrono_literals;
int main(int argc, char * argv[])
{
rclcpp::init(argc, argv);
auto node = rclcpp::Node::make_shared("publisher");
auto pub = node->create_publisher<std_msgs::msg::String>("/pub_sub", 10);
std_msgs::msg::String myMessage;
size_t counter{0};
rclcpp::WallRate loop_rate(500ms);
while (rclcpp::ok())
{
myMessage.data = "Hello, ros2 world! " + std::to_string(counter++);
RCLCPP_INFO(node->get_logger(), "Publishing: '%s'", myMessage.data.c_str());
try
{
pub->publish(myMessage);
rclcpp::spin_some(node);
} catch (const rclcpp::exceptions::RCLError & e)
{
RCLCPP_ERROR(node->get_logger(), "Errore type : %s", e.what());
}
loop_rate.sleep();
}
rclcpp::shutdown();
return 0;
}
2、subscriber
节点名 node = std::make_sharedrclcpp::Node(“subscriber”);
消息类型和话题 auto sub = node->create_subscription<std_msgs::msg::String>(“/pub_sub”, 10, TopicCallback);
回调函数 void TopicCallback(const std_msgs::msg::String::SharedPtr msg) //注意用::SharedPtr
回调函数消息 msg->data //注意用->
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"
std::shared_ptr<rclcpp::Node> node = nullptr;
void TopicCallback(const std_msgs::msg::String::SharedPtr msg)
{
RCLCPP_INFO(node->get_logger(), "I heard the message : '%s'", msg->data.c_str());
}
int main(int argc, char *argv[])
{
rclcpp::init(argc, argv);
node = std::make_shared<rclcpp::Node>("subscriber");
auto sub = node->create_subscription<std_msgs::msg::String>("/pub_sub", 10, TopicCallback);
rclcpp::spin(node);
rclcpp::shutdown();
return 0;
}
3、rqt_graph
4、延时sleep
rclcpp::WallRate loop_rate(500ms); //1s=1000ms,1ms=1000um,1um=1000nm
while (rclcpp::ok())
{
......
loop_rate.sleep();
}