Robotics StackExchange | Archived questions

Add a condition in a while loop

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.

Asked by LR1997 on 2021-04-21 07:29:43 UTC

Comments

Answers

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.

Asked by miura on 2021-04-21 08:49:45 UTC

Comments

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(..)?

Asked by gvdhoorn on 2021-04-21 09:40:20 UTC

@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();
    }

Asked by miura on 2021-04-21 10:18:05 UTC

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.

Asked by gvdhoorn on 2021-04-21 12:25:40 UTC

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

Asked by miura on 2021-04-22 10:52:14 UTC