Ask Your Question

Why does Subscriber have twist_pub ?

asked 2020-08-28 13:02:59 -0500

Zarkzeugan gravatar image

I am referring this book called "Programming with ROS" by Morgan Quigley. I am having difficulty understanding this particular code :

 Example 8-3.
#!/usr/bin/env python
import rospy
from std_msgs.msg import String
from geometry_msgs.msg import Twist
key_mapping = { 'w': [ 0, 1], 'x': [0, -1],
                'a': [-1, 0], 'd': [1, 0],
                's': [ 0, 0] }
g_last_twist = None
def keys_cb(msg, twist_pub):
    global g_last_twist
    if len( == 0 or not key_mapping.has_key([0]):
       return # unknown key
    vels = key_mapping[[0]]
    g_last_twist.angular.z = vels[0]
    g_last_twist.linear.x = vels[1]
if __name__ == '__main__':
   twist_pub = rospy.Publisher('cmd_vel', Twist, queue_size=1)
   rospy.Subscriber('keys', String, keys_cb, twist_pub)
   rate = rospy.Rate(10)
   g_last_twist = Twist() # initializes to zero
   while not rospy.is_shutdown():

So my question is : 1. Why does rospy.Subscriber('keys', String, keys_cb, twist_pub) have twist_ pub? 2. What is exactly happening in the while loop ?

while not rospy.is_shutdown():
edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2020-08-28 14:41:50 -0500

Quick summary:

  • Every time a message is published on the keys topic, the keys_cb callback is triggered, and the argument msg contains that latest message
  • Based on the data in the latest keys message, the keys_cb updates the value of the global variable g_last_twist.
  • The while loop you referenced runs at a rate of 10Hz and continually publishes the value of g_last_twist
  • The callback keys_cb is also passed a reference to the twist_pub publisher via the callback_args keyword argument in the constructor for a rospy.Subscriber. The callback also publishes the latest value of g_last_twist using its reference to the twist_pub-- presumably so you don't need to wait until the next iteration of the main while loop to get the value published.
edit flag offensive delete link more


So if i understand this correctly in the if statement, we are first initialising a node then we are setting cmd_vel as a Twist message topic we are subscribing to the keys topic which contains the callback and its argument and the function publishes g_last_twist then we set the rate to 10 Hz so the function runs 10 times in a second and then sleeps for the rest of the time. then we are initialising g_last_twist to 0 and the while loop takes the zero value?

Zarkzeugan gravatar image Zarkzeugan  ( 2020-08-29 13:28:00 -0500 )edit

Yeah. That all sounds about right

jarvisschultz gravatar image jarvisschultz  ( 2020-08-31 08:28:46 -0500 )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


Asked: 2020-08-28 13:02:59 -0500

Seen: 52 times

Last updated: Aug 28 '20