Exercise 6.2: where should we define the publisher object?

When I finish Exercise 6.2, why the robots only move when I define the publisher outside the callback function? And doesn’t work when I define it inside the callback function as follows

You have to initialize " pub " outside the callback. Otherwise, you create a new publisher instance every time the callback function is called.

Paste the line
pub = rospy.Publisher( …
behind my_service = rospy.Service(…

maybe you have to add “global pub” in the first line of your callback function

1 Like

I get your point. But could you explain more about the issue caused by creating a new publisher instance? From my understanding, even though the publisher object has been updated, if I can successfully publish the message, the robot should also move in circle. However, it is not the case here, when I run “rosservice call /move_bb8_in_circle [TAB]+[TAB]” with the above “wrong script”, the robot stays, the linear.x and angular.z seems not been updated successfully.

I think the problem is that you publish the Twist message exactly one time. If the subscriber isn’t already connected to the topic/publisher, then the message is lost.

If you create the publisher in the callback function, the subscriber has no time to subscribe to the topic and to receive the message while the publisher instance is destroyed directly afterward when the program is leaving the scope of the callback function.

You can wait in your callback function and check how many subscribers subscribed to your topic, and if one subscriber has subscribed then publish the message.

Hope this helps

Here is my solution

#! /usr/bin/env python

import rospy
from geometry_msgs.msg import Twist 
from std_srvs.srv import Empty, EmptyResponse 

twist = Twist()
twist.linear.x = 0.5
twist.linear.y = 0.0
twist.linear.z = 0.0
twist.angular.x = 0.0
twist.angular.y = 0.0
twist.angular.z = 0.5


def my_callback(request):
    global twist
    print("My_callback has been called")
    pub.publish(twist)
    return EmptyResponse() 

rospy.init_node('service_server') 
my_service = rospy.Service('/move_bb8_in_circle', Empty , my_callback)
pub = rospy.Publisher('/cmd_vel', Twist, queue_size=1)
rospy.spin()
1 Like