ROS2中std_msgs/msg/Headerr 数据含义及使用
- ROS官方消息说明
- 数据说明
- 使用ros2标准的Header案例
- 代码解释
- 测试结果
ROS官方消息说明
ROS2中std_msgs消息包含类型
https://docs.ros2.org/latest/api/std_msgs/msg/
std_msgs/msg/Header Message
std_msgs/msg/Header数据格式:
builtin_interfaces/msg/Time stamp #Two-integer timestamp that is expressed as seconds and nanoseconds.
string frame_id # Transform frame with which this data is associated.
数据说明
builtin_interfaces/msg/Time stamp
#时间戳,主要由秒和纳秒两部分构成
stamp有两个成员,分别为sec秒和nanosec纳秒
# int32 values.
int32 sec
#nanoseconds[0, 10e9).
uint32 nanosec
使用ros2标准的Header案例
程序实现功能:生成一个名字为test的节点,该节点主要发送两个话题数据,类型分别为std_msgs/msg/header,std_msgs/msg/string,实现代码如下:
#include <iostream>
#include <rclcpp/rclcpp.hpp>
#include <std_msgs/msg/header.hpp>
#include <std_msgs/msg/string.hpp>
#include <string>
#include <memory>
#include <chrono>
using namespace std;
class node:public rclcpp::Node{
public:
node(std::string name):Node(name){
pub_head = this->create_publisher<std_msgs::msg::Header>("header_topic", 10);
pub_string = this->create_publisher<std_msgs::msg::String>("string_topic", 10);
}
rclcpp::Publisher<std_msgs::msg::Header>::SharedPtr pub_head;
rclcpp::Publisher<std_msgs::msg::String>::SharedPtr pub_string;
};
int main(int argc, char**argv){
rclcpp::init(argc, argv);
std::shared_ptr<node> node_ptr = std::make_shared<node>("test");
std_msgs::msg::Header pub_header;
std_msgs::msg::String pub_string;
int i = 0;
rclcpp::Time t;
while(rclcpp::ok()){
i++;
pub_string.data = "num" + std::to_string(i);
pub_header.frame_id = "world";
// pub_header.stamp = std::chrono::system_clock::now();
pub_header.stamp = node_ptr->now();
node_ptr->pub_head->publish(pub_header);
node_ptr->pub_string->publish(pub_string);
sleep(1);
}
cout<<"hello_world!"<<endl;
}
代码解释
pub_header.stamp = node_ptr->now();
此处通过节点node_ptr来获取时间戳信息,并将值赋给要发布变量;
ROS获取时间的方式有很多种,具体可以参考一下内容:
https://blog.csdn.net/shoufei403/article/details/125955660
https://docs.ros2.org/bouncy/api/rclcpp/classrclcpp_1_1_time.html
推荐知乎ROS2获取当前系统时间的方法:
https://zhuanlan.zhihu.com/p/545431541?utm_id=0(
测试结果