Trouble with ROS basics in 5 days Topic quiz

Like the title says, I seem to have a bit of trouble getting topic quiz program to work. It runs but seems to get stuck in an infinite loop. I have consulted the solution but it takes a whole different approach than my effort, so I would like to know where I went wrong.

#! /usr/bin/env python

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

class MoveRobot:
    def __init__(self, speed):
        rospy.init_node('topics_quiz_node',anonymous=True)
        self.speed = speed
        self.time_turn = 7.0
        self.pub = rospy.Publisher('/cmd_vel', Twist, queue_size=1)
        self.sub = rospy.Subscriber('kobuki/laser/scan', LaserScan, self.callback)
        self.rate = rospy.Rate(2)
        self.cmd = Twist()


    def callback(self,msg):
        laser_msg = msg

    def get_front_laser(self):
        return self.laser_msg.ranges[360]


    def avoid_wall(self):
        while not rospy.is_shutdown():
            self.pub.publish(self.cmd)

            while self.get_front_laser > 1:
                self.cmd.linear.x = self.speed

            self.cmd.linear.x = 0
            self.cmd.angular.z = self.speed
            time.sleep(self.time_turn)
            self.cmd.linear.x = self.speed

            self.rate.sleep()

mr1 = MoveRobot(0.3)
mr1.avoid_wall()

You don’t need to call rospy.spin() because it is already taken into account by the rospy node you create. So the callback is automatically called whenever there is a laser data.

We use rospy.spin() just when we need to force the callbackqueue call, but it is very rarely used.

1 Like

@m.c.l.kamphuis your solution is quite compact and correct. Only a few small mistakes:

  1. you forgot to add the self prefix to the laser_msg in the callback.

  2. while self.get_front_laser > 1: is missing the ()

  3. actually the while block is kind of wrong. I would do it like this:

     if self.get_front_laser() > 1:
         self.cmd.linear.x = self.speed   
      else:
          self.cmd.linear.x = 0
1 Like