[ROS2] How to define a thread (control loop) along with subscriber's callbacks with the new rclcpp::spin()?
Hello, everyone, I'm using ROS2 Galactic
and I'm trying to define a control loop function that has to be periodic. In ROS1
I was using boost:thread
and then ros.spin()
to have all the callbacks to be executed, but now this procedure seems not to work because rclcpp::spin()
requires parameters. My situation is like that:
My Class
:
class ROBOT_INVDYN : public rclcpp::Node{
public:
//some stuff WITH SUBSCRIBERS...
void ctrl_loop();
private:
//other stuff...
};
the void ctrl_loop()
implementation:
void ROBOT_INVDYN::ctrl_loop() {
//INITIALIZATIONS...
rclcpp::Rate r(250);
while( rclcpp::ok() ) {
//PROPER CONTROL LOOP...
r.sleep();
}
}
then my main
int main (int argc, char * argv[]){
rclcpp::init(argc, argv);
auto robot_node = std::make_shared<ROBOT_INVDYN>();
//instruction that should make the ctrl loop as a periodic thread but doesn't work: so it's just an attempt
std::thread control_loop_t(robot_node->ctrl_loop);
rclcpp::spin(robot_node);
rclcpp::shutdown();
return 0;
}
In ros 1
I would have used a class function run():
void ROBOT_INVDYN::run() {
boost::thread ctrl_loop_t ( &ROBOT_INVDYN::ctrl_loop, this);
ros::spin();
}
and then modify the main
just to instanciate the class and call the run()
function.
What is the right way to make a similar thing in ros2
with the new rclcpp::spin()
?