while loop not updating global variable in cpp
hello everyone,
so i came across while loop not updating global variable in cpp
#include "ros/ros.h"
#include "std_msgs/Int32.h"
#include <fstream>
#include <iostream>
int op1;
int start= 0;
int right;
void rightCB(const std_msgs::Int32::ConstPtr& msg)
{
right=msg->data;
ROS_INFO("position of wheel1:[%d]",right);
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "encoder");
ros::NodeHandle n;
ros::Subscriber enc = n.subscribe<std_msgs::Int32>("/right", 1000,&rightCB);
while (ros::ok())
{
if(start == 0)
{
int distx = op1 + 100;
ROS_INFO("Distance range:[%d]",distx);
while(ros::ok())
{
ROS_INFO("position of wheel1:[%d]",right);
}
}
ros::spinOnce();
}
ros::spin();
return 0;
}
Asked by kallivalli on 2019-10-21 08:10:29 UTC
Answers
while(ros::ok())
{
ROS_INFO("position of wheel1:[%d]",right);
}
Your program reach this loop and do nothing else than ROS_INFO
. ROS doesn't process any callback if spin
or spinOnce
isn't called so you need to put the line ros::spinOnce()
in your loop.
Asked by Delb on 2019-10-21 08:38:36 UTC
Comments
Yes it's is what i was thinking. remove the internal while(ros::ok()) and give a chance to change the start parameter value!
Also, the
ros::spin();
is irrelevant if you use while loop + ros:spinOnce();
For me an, ideal main (correct me if I am wrong!):
int main(int argc, char **argv)
{
ros::init(argc, argv, "encoder");
ros::NodeHandle n;
ros::Subscriber enc = n.subscribe<std_msgs::Int32>("/right", 1000,&rightCB);
while (ros::ok())
{
if(start == 0)
{
int distx = op1 + 100;
ROS_INFO("Distance range:[%d]",distx);
start = 1; //?¿?¿?¿
}
ROS_INFO("position of wheel1:[%d]",right);
ros::spinOnce();
}
return 0;
}
But maybe also you should control a little the loop frequency :)
Asked by Solrac3589 on 2019-10-23 07:37:40 UTC
Comments