ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question
0

Timer Callback not getting called

asked 2023-05-31 04:57:38 -0500

GauNav gravatar image

Here Is My timer callback code



#include <ros ros.h="">
#include <stdio.h>
class Timer {
public:
    ros::NodeHandle nh_;
    Timer(ros::NodeHandle* nh) ;
    void init_timers();
    void stateTimerCallback(const ros::TimerEvent& event);

};

Timer::Timer(ros::NodeHandle* nh) : nh_(*nh) {
   Timer::init_timers();
}

void Timer::init_timers()
{
    const bool oneshot = false;
    bool autostart = true;
    ros::Timer timer_ = nh_.createTimer(ros::Duration(1.0),&Timer::stateTimerCallback,this,oneshot,autostart);
    timer_.start() ;
    ROS_INFO("Init_Timer \n");
    printf("Init_Timer\n");
    ROS_DEBUG("Init_Timer\n");

}

void Timer::stateTimerCallback(const ros::TimerEvent& event)
{
    ROS_INFO("I am here\n");
    printf("I am here\n");
    ROS_DEBUG("I am here\n");
}

int main(int argc, char **argv)
{
    ros::init(argc,argv,"timer_node");
    ros::NodeHandle nh;
    Timer timer(&nh);
    ros::spin();
    return 0;
}

The output i get after running the node


$ rosrun timertest timertest_node
[ INFO] [1685511182.674019058]: /timer_node: Init_Timer 

Init_Timer

I wait for 1 minute but still there was no output from callback. What might be the reason ?

edit retag flag offensive close merge delete

Comments

Really sorry if my question comes out as silly. I am not completely sure about working of roscpp.

GauNav gravatar image GauNav  ( 2023-05-31 06:45:59 -0500 )edit

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-05-31 10:23:38 -0500

bluegiraffe-sc gravatar image

Hi!

From the roscpp tutorials:

Note that, in this example, the timer object must be a member of the class for callbacks to fire.

Thus, you should have

class Timer {
public:
    ros::NodeHandle nh_;
    Timer(ros::NodeHandle* nh) ;
    void init_timers();
    void stateTimerCallback(const ros::TimerEvent& event);
    ros::Timer timer_;
};

and modify the line where you call nh_.createTimer() as follows:

timer_ = nh_.createTimer(ros::Duration(1.0),&Timer::stateTimerCallback,this,oneshot,autostart);

Hope this helps!

edit flag offensive delete link more

Comments

1

Summarising: the timer_ object only "exists" as long as init_timers() is executing. Which is perhaps a couple hundred nanoseconds. It then immediately gets destroyed. No timer_ -> no callbacks.

gvdhoorn gravatar image gvdhoorn  ( 2023-05-31 14:51:08 -0500 )edit
GauNav gravatar image GauNav  ( 2023-06-01 01:12:35 -0500 )edit

Question Tools

1 follower

Stats

Asked: 2023-05-31 00:53:20 -0500

Seen: 159 times

Last updated: May 31 '23