Topics Quiz: Robot move toward the wall successfully, but ranges[360] value always return around 2.5m. Please help

#! /usr/bin/env python

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

def mycallback(msg):

    print msg.ranges[360]

    if msg.ranges[360] < 1.5:
        pos.angular.z += 0.1

    if msg.ranges[360] > 1.5 and msg.ranges[360] < 30:
        pos.linear.x += 0.1

pub = rospy.Publisher('/cmd_vel',Twist, queue_size=1)
rate = rospy.Rate(1)
pos = Twist()
sub = rospy.Subscriber('/kobuki/laser/scan', LaserScan, mycallback)

Hi @etiennebouthiette,

First of all, welcome to the community!

The error you have described is quite strange, as the value should become smaller as the robot moves towards the wall. Please try the following hints and try again. I suspect hints 1 and 2 may be the culprits here, 2 especially!

  1. Remove the rospy.Rate object from your program completely - you don’t need it here.

  2. Try refining the robot movement logic like this:

# This snippet ensures that when the robot is close to the wall, linear movement is stopped and
# the robot turns. Otherwise, angular movement (turning) is stopped and linear movement continues
# 1.5 may not be the optimal value, check the actual value when the robot is close to the wall
if msg.ranges[360] < 1.5: 
  pos.angular.z = 0.1
  pos.linear.x = 0.0
  pos.angular.z = 0.0
  pos.linear.x = 0.1


With your current code, linear and angular movement is always present, so I imagine that the robot might be moving in circles somewhat, instead of moving forward. Also, by using += for the speed, you’re always increasing it, predisposing the robot to erratic movement.

  1. You’re expecting msg.ranges[360] to have a value up to 30, but it really does not get that high in the simulation. Appears to be up to 3.0.

Thank you bayodesegun.
It works now.
The rospy.Rate had to be removed like you suggested to receive the LaserScan data in real time.
I changed the logic like you suggested. I was confusing position and speed.

Best regards

1 Like