Search code examples
pythonros

Callback function does not change value of local variables (ROS)


So I have a problem that asks me to rotate my robot facing the wall. I created a callback function for my subscriber and I am trying to compute its values in the function. Here is the code:

def callback(msg):
  r = list(msg.ranges)
  minimum_value = min(r)
  print(minimum_value)
  index_minimum = r.index(minimum_value)
  rounded_min = round(minimum_value,3)
  print('min index',index_minimum)

  if index_minimum > 360:
      twist_instance.angular.z = 0.05
  else:
      twist_instance.angular.z = -0.05
  while round(msg.ranges[360],3) != rounded_min:
      print('rounded min', rounded_min)
      print('front ',round(msg.ranges[360],3))
      print('index naya', index_minimum)
      pub.publish(twist_instance)
      rate.sleep()
  twist_instance.linear.x = 0.1
  twist_instance.angular.z = 0
  while round(msg.ranges[360],1) >= 0.3:
      pub.publish(twist_instance)
      rate.sleep()
  twist_instance.linear.x = 0
  pub.publish(twist_instance)

if __name__ == '__main__':
    rospy.init_node('findwall_node')
    sub = rospy.Subscriber('/scan', LaserScan, callback)
    pub = rospy.Publisher('/cmd_vel', Twist, queue_size=1)    
    twist_instance = Twist()
    rate = rospy.Rate(1)
    my_service = rospy.Service('/find_wall', findwall, my_callback)
    rospy.spin()

I am printing out the values just for a reference. Here the r = list(msg.ranges) has index range from 0 to 719 and they represent laser values from 0 to 180 degrees respectively. As the robot rotates the values will change at the same time but thats the problem I face. They do not!. I printed out the values in the loop and the values for each of them always remain constant. Can you help me understand why that is?


Solution

  • I think it is because you are using a loop inside the callback, in the line while round(msg.ranges[360],3) != rounded_min. Then, the callback gets "stuck", and it is called only once, causing msg.ranges to remain constant. However, I am not able to test your code just now.