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

Add a condition in a while loop

asked 2021-04-21 07:29:43 -0500

LR1997 gravatar image

Hi guys, I was wondering how is it possible to introduce a condition in a standard spin function. More precisely: at the moment the spin function for my code looks like:

    ros::Rate loop(frequency);
    while(ros::ok()){
    //do some computations and publish messages
    loop.sleep();
    ros::spinOnce();
    }

By doing so, the computations and publish messages are executed at every loop. I would now like to introduce the following condition:

do the computation and publish messages only if a new message on the topic A is received.

So the new spin function should look like:

 ros::Rate loop(frequency);
    while(ros::ok()){
    if (new message on topic A is received){
//do some computations and publish messages
}
    loop.sleep();
    ros::spinOnce();
    }

I would like to ask you what is the best way to introduce this condition.

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-04-21 08:49:45 -0500

miura gravatar image

updated 2021-04-21 08:50:06 -0500

I would do the following.

bool is_receive;

void callback_topic_A(msgtype &msg)
{
    is_receive = true;
}

// ...
    ros::Rate loop(frequency);
    is_receive = false;
    while(ros::ok()){
        if (is_receive){
            //do some computations and publish messages
            is_receive = false;
        }
        loop.sleep();
        ros::spinOnce();
    }

If there is a better way, I would love to know.

edit flag offensive delete link more

Comments

2

The OP asked how to:

do the computation and publish messages only if a new message on the topic A is received.

why not "do the computation and publish the messages" in callback_topic_A(..)?

gvdhoorn gravatar image gvdhoorn  ( 2021-04-21 09:40:20 -0500 )edit

@gvdhoorn That's good, too. This is how it's done, right?

void callback_topic_A(msgtype &msg)
{
    //do some computations and publish messages
}

// ...
    ros::Rate loop(frequency);
    while(ros::ok()){
        loop.sleep();
        ros::spinOnce();
    }
miura gravatar image miura  ( 2021-04-21 10:18:05 -0500 )edit
1

I don't believe you'd need to run your own while loop any more in that case.

It's not doing anything which ros::spin() is not already doing.

gvdhoorn gravatar image gvdhoorn  ( 2021-04-21 12:25:40 -0500 )edit

You're right. Now it depends on how LR1997 will update the function.

miura gravatar image miura  ( 2021-04-22 10:52:14 -0500 )edit

Question Tools

1 follower

Stats

Asked: 2021-04-21 07:29:43 -0500

Seen: 630 times

Last updated: Apr 21 '21