akhil0_0
akhil0_0

Reputation: 36

How can we use Twist() to rotate turtle two times making different circles in ROS python?

I want to move the turtle in circle two times making two different circles, and I'm using Twist() but when ever I give two different twist and values for the same publisher only one for them is published, even I have tried using two different publishers, but getting the same output. So anyone can please tell me how to publish the Twist() with two different values.

 pub = rospy.Publisher('turtle1/cmd_vel', Twist, queue_size=10)
 pub_1 = rospy.Publisher('turtle1/cmd_vel', Twist, queue_size=10)

 # Create a Twist message and add linear x and angular z values
 move_cmd = Twist()
 move_cmd.linear.x =   1.0
 move_cmd.linear.y =   0.0
 move_cmd.angular.z = -1.0
 move_cmd_1 = Twist()
 move_cmd_1.linear.x =  1.0
 move_cmd_1.linear.y =  0.0
 move_cmd_1.angular.z = 1.0

 # Save current time and set publish rate at 10 Hz
 now = rospy.Time.now()
 rate = rospy.Rate(10)

 # For the next 6 seconds publish cmd_vel move commands to Turtlesim
 while rospy.Time.now() < now + rospy.Duration.from_sec(10.5):
     pub.publish(move_cmd_1)

     pub_1.publish(move_cmd_1)
     rate.sleep()

Upvotes: 1

Views: 1301

Answers (1)

BTables
BTables

Reputation: 4843

There are a couple of things wrong with your code here. First, you're actually publishing the same message on both publishers. Secondly, it's not a good idea to publish two values on the same topic right after each other like that. If the subscriber is caching the most recent value there is a very good chance it will only ever see/use the second value published. If you're trying to alternate, try this code instead. Note that I decreased the spin rate and the publishers are alternating per loop.

 pub = rospy.Publisher('turtle1/cmd_vel', Twist, queue_size=10)

 # Create a Twist message and add linear x and angular z values
 move_cmd = Twist()
 move_cmd.linear.x =   1.0
 move_cmd.linear.y =   0.0
 move_cmd.angular.z = -1.0
 move_cmd_1 = Twist()
 move_cmd_1.linear.x =  1.0
 move_cmd_1.linear.y =  0.0
 move_cmd_1.angular.z = 1.0

 # Save current time and set publish rate at 10 Hz
 now = rospy.Time.now()
 rate = rospy.Rate(3)
 loop_count = 0

 # For the next 6 seconds publish cmd_vel move commands to Turtlesim
 while rospy.Time.now() < now + rospy.Duration.from_sec(10.5):
     if loop_count % 2 == 0:
         pub.publish(move_cmd)
     else:
         pub.publish(move_cmd_1)
     loop_count += 1
     rate.sleep()

Upvotes: 0

Related Questions