0
$\begingroup$

Rosanswers logo

Hi,

I want to stop publishing a message to a topic after 20 iterations. For that I have written the following piece of code, but however the counter reaches to 20, the program is still publishing the message to the topic and it seems that it is disregarding the counter variable's value. How can I resolve this issue?

class node():



def __init__(self):

    rosInstance = rospy
    pub = rosInstance.Publisher('cmd_vel', Twist)
    r = rosInstance.Rate(1)
    ctrlArgs = Twist()
    iteration = 0
    speed = -0.1


    while not rospy.is_shutdown():
        self.iterate()
        if iteration < 20:
            cntrlArgs.linear.x = 0.2
            pub.publish(ctrlArgs)
        r.sleep()


def iterate(self):
    iteration = iteration + 1

And then I run the program:

if __name__ == '__main__':

    rospy.init_node('iterator', anonymous=False)
    try:
        nn = node()
    except rospy.ROSInterruptException: pass

Thank you


Originally posted by Warrior on ROS Answers with karma: 61 on 2014-04-06

Post score: 0

$\endgroup$

2 Answers 2

0
$\begingroup$

Rosanswers logo

iteration here is a local variable, not a member variable of your class. So the variable you iterate in the iterate() function is completely different than the variable you check in your loop. Use self.iteration instead of iteration.


Originally posted by jbinney with karma: 606 on 2014-04-06

This answer was NOT ACCEPTED on the original site

Post score: 2


Original comments

Comment by Warrior on 2014-04-06:
I just did. I added the self. prefix to the iteration variable in the iterate() function. Now the program doesn't show me an error, but still doesn't stop the robot moving ... . I really need to resolve this issue.

Comment by jbinney on 2014-04-06:
You'll have to post the updated code if you want help finding your bug

Comment by Warrior on 2014-04-15:
Sorry for the delay. I found the solution to the problem and answered my question.

$\endgroup$
0
$\begingroup$

Rosanswers logo

The issue is resolved now. I had to add "self." as prefix to all of the variables that I wanted to consider as "global" in a specific class.

Here's the modified code:

class node():



def __init__(self):

    rosInstance = rospy
    self.pub = rosInstance.Publisher('cmd_vel', Twist)
    r = rosInstance.Rate(1)
    self.ctrlArgs = Twist()
    self.iteration = 0
    speed = -0.1


    while not rospy.is_shutdown():
        self.iterate()
        if iteration < 20:
            self.cntrlArgs.linear.x = 0.2
            self.pub.publish(ctrlArgs)
        r.sleep()


def iterate(self):
    self.iteration = self.iteration + 1

Originally posted by Warrior with karma: 61 on 2014-04-15

This answer was ACCEPTED on the original site

Post score: 0

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.