Robotics StackExchange | Archived questions

Callback of subscriber only works after publishing 3-4 times depending on topic.

Here's the part of the publisher code

def publish_data(topic, message):
    pub = rospy.Publisher(topic, UInt16, queue_size=100)
    rospy.init_node('Talker', anonymous=True)
    pub.publish(message)
    rospy.loginfo("MSG PUB LUL")
    rate = rospy.Rate(20) # publish at 10 Hz
    rate.sleep()

and this is the whole subscriber code:

import rospy
from std_msgs.msg import String
from std_msgs.msg import UInt16


def callback(servo_num, data):
    print("Callback function called with servo_num:", servo_num, "and data:", data.data)
    rospy.loginfo("Servo{}".format(servo_num))
    rospy.loginfo(data.data)

def listener():

    rospy.init_node('listener', anonymous=True)
    rospy.Subscriber("Servo1", UInt16, lambda data: callback(1, data))
    rospy.Subscriber("Servo2", UInt16, lambda data: callback(2, data))
    rospy.Subscriber("Servo3", UInt16, lambda data: callback(3, data))
    rospy.Subscriber("Servo4", UInt16, lambda data: callback(4, data))
    rospy.Subscriber("Servo5", UInt16, lambda data: callback(5, data))
    rospy.Subscriber("Servo6", UInt16, lambda data: callback(6, data))

    rospy.spin()

if __name__ == '__main__':
    listener()

When trying to publish the messages the rospy.loginfo("MSG PUB LUL") is out in the terminal with no problem. The problem is on the other side, that only outputs the print("Callback function called with servo_num:", servo_num, "and data:", data.data) after 2-3 times of publishing on the same topic. if the callback get called once, it will get called again with no problem unless i restart my code. Something i observer is that the 2-3 time may happen to be 3-4 times if the rate became too high like 200 or so. But if i try to put rate = 1 it doesn't really change much, same 2-m times of publishing to void before actually appearing.

Anyone encountered the same problem? Could really use some help here. Thanks in advance!

Asked by Shaheen on 2023-04-24 20:21:10 UTC

Comments

Hi!

Could you please post more of the publisher code, and describe a little bit more in detail your application?

The publisher snippet you posted looks odd to me... You usually define the Rate object outside a loop, and place the rate.sleep() as the last line of the loop. Here it looks like both operations happen inside the loop.

Moreover, how are you launching the talker and listener? Do you use rosrun in two separate terminals or a single roslaunch command?

Asked by bluegiraffe-sc on 2023-05-29 08:01:17 UTC

Answers