How to structure code inside a node
Hi, I'm learning ROS and I was wondering how should I write the code inside my nodes.
Let's take this example: The node should control the movement of a robot (publishing a velocity command) but at the same time check received messages from a sensor.
I also need to set the velocity gradually I can easily achieve this using a loop. But this avoid my node from calling the ros::Spin() and so the callback updating my global variables (or class members) is never called, right?
So I think I am supposed to make the code inside an infinite loop which calls ros::spinOnce() and write the code to control the robot in such a way that it doesn't block the loop?
I'm not sure I have been very clear, but I hope someone can point me in the right direction, thanks.
EDIT = I thought about something that could be smart in my case (mainly for readibility reasons) The switch/case. (I need to perform multiple action and I can't execute the next until i finished the previous or the sensor detect something. See:
while(nh.ok())
{
switch(STATUS)
{
case 1:
inc_vel();
if (object detected) //global variable updated by the sensor callback
{
stop();
STATUS++;
}
break;
case 2:
//do something else, for example turn around and change path
break;
}
ros::spinOnce();
}