ros2中的定时器
rclcpp::TimerBase::SharedPtr
这是ros2终端定时器的类型;
定时器创建
需要使用rclcpp::Node中的接口创建:
rclcpp::TimerBase::SharedPtr timer_=this->create_wall_timer()
Node::create_wall_timer()
template<typename DurationRepT, typename DurationT, typename CallbackT>
typename rclcpp::WallTimer<CallbackT>::SharedPtr
Node::create_wall_timer(
std::chrono::duration<DurationRepT, DurationT> period,
CallbackT callback,
rclcpp::CallbackGroup::SharedPtr group)
{
return rclcpp::create_wall_timer(
period,
std::move(callback),
group,
this->node_base_.get(),
this->node_timers_.get());
}
函数接受三个参数:
`period` 为时间间隔,即回调函数执行的时间间隔;
`callback` 为回调函数,当计时器触发时执行;
`group` 为指定的回调函数组,所有使用同一回调组的定时器将一起触发回调,可不传递。
class PublisherNode:public rclcpp::Node{
public:
PublisherNode(std::string name):Node(name){
publisher_=this->create_publisher<std_msgs::msg::String>("topic_01",10);
timer_=this->create_wall_timer(500ms,std::bind(&PublisherNode::_timer_callback,this));
}
private:
void timer_callback(){
auto msg=std_msgs::msg::String();
msg.data="hello world!";
publisher_->publish(msg);
RCLCPP_INFO(this->get_logger(),"Pulishing: '%s'",msg.data.c_str());
}
rclcpp::TimerBase::SharedPtr timer_{};
rclcpp::Publisher<std_msgs::msg::String>::SharedPtr publisher_{};
};
ros2中如何获取当前时间
this->get_clock()->now()