Topics quiz help

I’m getting a little bit frustrating as I’ve been unable to perform this task.

I don’t understand why I can’t get the info from the callback function. Any help?

#! /usr/bin/env python

import rospy
from geometry_msgs.msg import Twist
from sensor_msgs.msg import LaserScan


def callback(msg):
    global laser_msg
    laser_msg = msg

rospy.init_node('topics_quiz_node', anonymous=True)
pub = rospy.Publisher('/cmd_vel', Twist, queue_size=1)
sub = rospy.Subscriber('/kobuki/laser/scan', LaserScan, callback)

rate = rospy.Rate(2)
move = Twist()
move.linear.x = 0.5

while not rospy.is_shutdown():
    pub.publish(move)
    print(laser_msg.ranges[360])
    rate.sleep()

Hi @pablotorneiro,

It seems you’re trying to access the LaserScan message outside the callback. If that is the case, you can try this instead:

#! /usr/bin/env python

import rospy
from geometry_msgs.msg import Twist
from sensor_msgs.msg import LaserScan


def callback(msg):
    # laser_msg is automatically available here because it's defined globally
    # similarly, pub, move are accessible here (but move their definition before `sub`)
    laser_msg = msg

rospy.init_node('topics_quiz_node', anonymous=True)
pub = rospy.Publisher('/cmd_vel', Twist, queue_size=1)
laser_msg = None # define laser_msg globally, before the callback is called
sub = rospy.Subscriber('/kobuki/laser/scan', LaserScan, callback)

rate = rospy.Rate(2)
move = Twist()
move.linear.x = 0.5

while not rospy.is_shutdown():
    pub.publish(move)
    if laser_msg: # it remanins None until the callback is called for the 1st time
        print(laser_msg.ranges[360])
    rate.sleep()

That said, I don’t understand what you are trying to do by accessing the LaserScan message outside the callback. Consider putting your robot control logic right inside the callback:

  • Any debugging of the LaserScan message (such as this print statement)
  • Moving the robot (since this should depend on the LaserScan message)
2 Likes

Thanks for your help.

I finally managed to get to the solution according to your suggestion.

Kind regards :hugs:

1 Like