Unit 3: Topics - Subscribers and Messages

Respected Professor,
I’m trying the quiz in Unit 3 of Basics of ROS. I tried the following two type of codes shown in screenshots:

Error: It throws the error saying that the msg is not defined. I can understand that it’s because the msg is defined only in the function.

2. Second Try

Error: This also throws an error saying that callback is not defined. I don’t understand the reason for this error.

3. May I please get some help in this quiz? I’m confused in few things:
a What is rospy.spin()? And, Do we need rospy.spin() in this code where publisher and subscriber is in the same document? Because usually we used to write rospy.spin() command whenever we created a Subscriber individually. If we don’t need to write it here, why?
b If I write a function def callback(msg) , it will be outside the while. And the publisher data is in the while loop. As Publisher gives velocity and Subscriber gives distance, How do I combine the subscriber with the publisher, so that I’ll be able to control the motion w.r.t distance?
c If my approach is wrong in part b or I’m totally wrong overall, please guide me to the correct approach to solve the quiz

Hi @abdulbasitisdost,

Since this is a Quiz, we can’t tell you the answers here or review your code :slight_smile:. That said, if you search this forum you will find some hints on your queries.

Also, you need to ensure your code has followed Python best practises for variable scopes.