alternative to rospy.Rate() and rate.sleep()

asked 2020-05-27 23:55:25 -0500

yabdulra gravatar image

Hi, I have epuck2 robot which I connect with via Bluetooth using epuck_driver package provided by GCTronic. I'm trying to implement wall following algorithm so I could traverse a small maze I built. I have this piece of code I got from "theconstruct" as below:

    #!/usr/bin/env python

# import ros stuff
import rospy
from sensor_msgs.msg import LaserScan
from geometry_msgs.msg import Twist
from nav_msgs.msg import Odometry
from tf import transformations
import time
import math

pub_ = None
regions_ = {
    'right': 0,
    'fright': 0,
    'front': 0,
    'fleft': 0,
    'left': 0,
}
state_ = 0
state_dict_ = {
    0: 'find the wall',
    1: 'turn left',
    2: 'follow the wall',
}


def clbk_laser(msg):
    global regions_
    regions_ = {
        'right':  min(min(msg.ranges[0:3]), 1),
        'fright': min(min(msg.ranges[4:7]), 1),
        'front':  min(min(msg.ranges[8:10]), 1),
        'fleft':  min(min(msg.ranges[11:14]), 1),
        'left':   min(min(msg.ranges[15:18]), 1),
    }

###this is just a portion of the code###

def main():
    global pub_

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

    pub_ = rospy.Publisher('/mobile_base/cmd_vel', Twist, queue_size=1)

    sub = rospy.Subscriber('/scan', LaserScan, clbk_laser)
    rate = rospy.Rate(20)
    while not rospy.is_shutdown():
        msg = Twist()
        if state_ == 0:
            msg = find_wall()
        elif state_ == 1:
            msg = turn_left()
        elif state_ == 2:
            msg = follow_the_wall()
            pass
        else:
            rospy.logerr('Unknown state!')

        pub_.publish(msg)
        rate.sleep()


if __name__ == '__main__':
     main()

the driver I'm using warn users not to call rate.sleep to maintain connection with the robot. I was able to connect with the robot, but it fail and get connected again with the rate.sleep() called. Removing the rate.sleep() is publishing just once and stuck the robot to finding wall. I tried using rospy.spin() instead(though i know it is mostly used when subscribing only) and no velocity command is published. Could anyone please tell an altenative to using rate.sleep() so I could get velocity commands published to the cmd_vel topic? Thanks

edit retag flag offensive close merge delete