Ask Your Question
0

while loop not updating global variable in cpp

asked 2019-10-21 08:10:29 -0600

kallivalli gravatar image

updated 2019-10-21 08:11:53 -0600

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;
    }
edit retag flag offensive close merge delete

1 Answer

Sort by » oldest newest most voted
2

answered 2019-10-21 08:38:36 -0600

Delb gravatar image
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.

edit flag offensive delete link more

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 :)

Solrac3589 gravatar imageSolrac3589 ( 2019-10-23 07:37:40 -0600 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

2 followers

Stats

Asked: 2019-10-21 08:10:29 -0600

Seen: 15 times

Last updated: Oct 21