Unit4 - Topics Quiz - confused abt callback and subscribers

After spending hours on it and being very frustrated, I am now asking for help. :face_with_symbols_over_mouth: :face_with_symbols_over_mouth:

What I want to do here is simply retrieve the data from the scan and move forward if the wall is further than 1m. Period!

I think there is something fundamental that I get wrong about callback functions.

#!/usr/bin/env python
# license removed for brevity
import rospy
from sensor_msgs.msg import LaserScan
from geometry_msgs.msg import Twist

def callback(msg): 
  laser_msg = msg
  print(laser_msg)
  return laser_msg


rospy.init_node('move_node', anonymous=True)

pub = rospy.Publisher('/cmd_vel', Twist, queue_size=10)           # defining the publisher
sub = rospy.Subscriber('/kokubi/laser/scan', LaserScan, callback) # defining the subscriber
rate = rospy.Rate(10) # 10hz

vel = Twist()



front_dist = laser_msg.ranges[360]

while not rospy.is_shutdown():
    while front_dist>1:
        vel.linear.x = 0.5
        pub.publish(vel)
        rate.sleep()
        front_dist = laser_msg.ranges[360]
    else:
        vel.linear.x = 0
        pub.publish(vel)

Here is the error message I get:

I think what I don’t get is in the callback function at line 7. In my understanding the callback function allows to store the message containing the laserscan values. I am using those values in the while not rospy.is_shutdown(): loop to control the robot speed. But given the error message there is something wrong: ‘laser_msg’ is not defined

Can someone help me on that because I am getting discouraged!

Hi,

You should be putting everything from your main program inside a

if __name__=='__main__':

After your callback definition. I don’t see that anywhere so it might be giving your problems.
After having that structure, you can try only outputting the values of the scan, that way you’ll know your subscriber/callback is working as it should. Finally, you can tackle the manipulation of this data.

It is very helpful to break down your programs like this to identify where the issue is coming from.

It could be because laser_msg is defined in the callback function, so the scope of laser_msg is inside callback only.