Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2017
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.30 KB | None | 0 0
  1. #!/usr/bin/env python
  2. import rospy
  3. from sensor_msgs.msg import LaserScan
  4. from std_msgs.msg import String, Header
  5. from ackermann_msgs.msg import AckermannDriveStamped
  6.  
  7.  
  8. import numpy as np
  9. from sklearn.decomposition import PCA
  10.  
  11. """
  12. Author: Ariel Anders
  13. This program tells the robot to follow a wall.
  14.  
  15. Edited by: Winter Guerra
  16. """
  17.  
  18. class WallFollower():
  19.     def __init__(self):
  20.         '''
  21.        Init the node. See safety.py for a good idea of what to do.
  22.        '''
  23.  
  24.  
  25.         # Init subscribers and publishers
  26.         self.sub = rospy.Subscriber("/scan", LaserScan,\
  27.                 self.lidarCB, queue_size=1)
  28.  
  29.         self.pub = rospy.Publisher("/vesc/low_level/ackermann_cmd_mux/input/safety",\
  30.                 AckermannDriveStamped, queue_size =1 )
  31.  
  32.         rospy.loginfo("Safety node initialized")
  33.         self.count = 0
  34.  
  35.  
  36.     def lidarCB(self, msg):
  37.         '''
  38.        This callback is called everytime the laserscanner sends us data.
  39.        This is about 40hz. The message received is a laserscan message
  40.        '''
  41.         angles = np.linspace(-2./3 * np.pi, -np.pi/6, 405)
  42.         distances = np.array(msg.ranges)
  43.         distances = distances[0:405]
  44.         valid_indices = msg.range_min < distances < msg.range_max
  45.         rect_dist = distances[valid_indices]
  46.         rect_ang = angles[valid_indices]
  47.  
  48.         cart_x = rect_dist*np.cos(rect_ang)
  49.         cart_y = rect_dist*np.sin(rect_ang)
  50.  
  51.         cart = np.column_stack((cart_x, cart_y))
  52.         pca = PCA(n_components=2)
  53.         pca.fit(cart)
  54.         wall_angle = np.arctan(pca.components_[0, 1]/pca.components_[0, 0])
  55.  
  56.         # vector to median point, use median point to compute distance
  57.         median_vec = np.array([np.median(cart_x), np.median(cart_y)])
  58.         wall_vector = pca.components_[0]
  59.         wall_vector /= np.linalg.norm(wall_vector)
  60.  
  61.         # vector represneting the perpendicular to wall
  62.         perp_vector = (1 - median_vec.dot(wall_vector)) * median_vec
  63.         distance = np.linalg.norm(perp_vector)
  64.  
  65.         self.follow_wall(distance, wall_angle)
  66.  
  67.  
  68. if __name__=="__main__":
  69.     # Tell ROS that we're making a new node.
  70.     rospy.init_node("Wall_Follower_Node")
  71.  
  72.     # Init the node
  73.     WallFollower()
  74.  
  75.     # Don't let this script exit while ROS is still running
  76.     rospy.spin()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement