You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

173 lines
6.7 KiB

2 years ago
  1. ## Example 3
  2. The aim of example 3 is to combine the two previous examples and have Stretch utilize its laser scan data to avoid collision with objects as it drives forward.
  3. Begin by running the following commands in a new terminal.
  4. ```bash
  5. # Terminal 1
  6. roslaunch stretch_core stretch_driver.launch
  7. ```
  8. Then in a new terminal type the following to activate the LiDAR sensor.
  9. ```bash
  10. # Terminal 2
  11. roslaunch stretch_core rplidar.launch
  12. ```
  13. To set *navigation* mode and to activate the [avoider.py](https://github.com/hello-robot/stretch_tutorials/blob/main/src/avoider.py) node, type the following in a new terminal.
  14. ```bash
  15. # Terminal 3
  16. rosservice call /switch_to_navigation_mode
  17. cd catkin_ws/src/stretch_tutorials/src/
  18. python avoider.py
  19. ```
  20. To stop the node from sending twist messages, type **Ctrl** + **c** in the terminal running the avoider node.
  21. <p align="center">
  22. <img height=600 src="https://raw.githubusercontent.com/hello-robot/stretch_tutorials/main/images/avoider.gif"/>
  23. </p>
  24. ### The Code
  25. ```python
  26. #!/usr/bin/env python
  27. import rospy
  28. from numpy import linspace, inf, tanh
  29. from math import sin
  30. from geometry_msgs.msg import Twist
  31. from sensor_msgs.msg import LaserScan
  32. class Avoider:
  33. """
  34. A class that implements both a LaserScan filter and base velocity control
  35. for collision avoidance.
  36. """
  37. def __init__(self):
  38. """
  39. Function that initializes the subscriber, publisher, and marker features.
  40. :param self: The self reference.
  41. """
  42. self.pub = rospy.Publisher('/stretch/cmd_vel', Twist, queue_size=1) #/stretch_diff_drive_controller/cmd_vel for gazebo
  43. self.sub = rospy.Subscriber('/scan', LaserScan, self.set_speed)
  44. self.width = 1
  45. self.extent = self.width / 2.0
  46. self.distance = 0.5
  47. self.twist = Twist()
  48. self.twist.linear.x = 0.0
  49. self.twist.linear.y = 0.0
  50. self.twist.linear.z = 0.0
  51. self.twist.angular.x = 0.0
  52. self.twist.angular.y = 0.0
  53. self.twist.angular.z = 0.0
  54. def set_speed(self,msg):
  55. """
  56. Callback function to deal with incoming LaserScan messages.
  57. :param self: The self reference.
  58. :param msg: The subscribed LaserScan message.
  59. :publishes self.twist: Twist message.
  60. """
  61. angles = linspace(msg.angle_min, msg.angle_max, len(msg.ranges))
  62. points = [r * sin(theta) if (theta < -2.5 or theta > 2.5) else inf for r,theta in zip(msg.ranges, angles)]
  63. new_ranges = [r if abs(y) < self.extent else inf for r,y in zip(msg.ranges, points)]
  64. error = min(new_ranges) - self.distance
  65. self.twist.linear.x = tanh(error) if (error > 0.05 or error < -0.05) else 0
  66. self.pub.publish(self.twist)
  67. if __name__ == '__main__':
  68. rospy.init_node('avoider')
  69. Avoider()
  70. rospy.spin()
  71. ```
  72. ### The Code Explained
  73. Now let's break the code down.
  74. ```python
  75. #!/usr/bin/env python
  76. ```
  77. Every Python ROS [Node](http://wiki.ros.org/Nodes) will have this declaration at the top. The first line makes sure your script is executed as a Python script.
  78. ```python
  79. import rospy
  80. from numpy import linspace, inf, tanh
  81. from math import sin
  82. from geometry_msgs.msg import Twist
  83. from sensor_msgs.msg import LaserScan
  84. ```
  85. You need to import rospy if you are writing a ROS [Node](http://wiki.ros.org/Nodes). There are functions from `numpy` and `math` that are required within this code, thus linspace, inf, tanh, and sin are imported. The `sensor_msgs.msg` import is so that we can subscribe to `LaserScan` messages. The `geometry_msgs.msg` import is so that we can send velocity commands to the robot.
  86. ```python
  87. self.pub = rospy.Publisher('/stretch/cmd_vel', Twist, queue_size=1)#/stretch_diff_drive_controller/cmd_vel for gazebo
  88. ```
  89. This section of code defines the talker's interface to the rest of ROS. `pub = rospy.Publisher("/stretch/cmd_vel", Twist, queue_size=1)` declares that your node is publishing to the */stretch/cmd_vel* topic using the message type `Twist`.
  90. ```python
  91. self.sub = rospy.Subscriber('/scan', LaserScan, self.set_speed)
  92. ```
  93. Set up a subscriber. We're going to subscribe to the topic "*scan*", looking for `LaserScan` messages. When a message comes in, ROS is going to pass it to the function "set_speed" automatically.
  94. ```python
  95. self.width = 1
  96. self.extent = self.width / 2.0
  97. self.distance = 0.5
  98. ```
  99. *self.width* is the width of the laser scan we want in front of Stretch. Since Stretch's front is pointing in the x-axis, any points with y coordinates further than half of the defined width (*self.extent*) from the x-axis are not considered. *self.distance* defines the stopping distance from an object.
  100. ```python
  101. self.twist = Twist()
  102. self.twist.linear.x = 0.0
  103. self.twist.linear.y = 0.0
  104. self.twist.linear.z = 0.0
  105. self.twist.angular.x = 0.0
  106. self.twist.angular.y = 0.0
  107. self.twist.angular.z = 0.0
  108. ```
  109. Allocate a `Twist` to use, and set everything to zero. We're going to do this when the class is initiating. Redefining this within the callback function, `set_speed()` can be more computationally taxing.
  110. ```python
  111. angles = linspace(msg.angle_min, msg.angle_max, len(msg.ranges))
  112. points = [r * sin(theta) if (theta < -2.5 or theta > 2.5) else inf for r,theta in zip(msg.ranges, angles)]
  113. new_ranges = [r if abs(y) < self.extent else inf for r,y in zip(msg.ranges, points)]
  114. ```
  115. This line of code utilizes linspace to compute each angle of the subscribed scan. Here we compute the y coordinates of the ranges that are below -2.5 and above 2.5 radians of the scan angles. These limits are sufficient for considering scan ranges in front of Stretch, but these values can be altered to your preference. If the absolute value of a point's y-coordinate is under self.extent then keep the range, otherwise use inf, which means "no return".
  116. ```python
  117. error = min(new_ranges) - self.distance
  118. ```
  119. Calculate the difference of the closest measured scan and where we want the robot to stop. We define this as *error*.
  120. ```python
  121. self.twist.linear.x = tanh(error) if (error > 0.05 or error < -0.05) else 0
  122. ```
  123. Set the speed according to a tanh function. This method gives a nice smooth mapping from distance to speed, and asymptotes at +/- 1
  124. ```python
  125. self.pub.publish(self.twist)
  126. ```
  127. Publish the `Twist` message.
  128. ```python
  129. rospy.init_node('avoider')
  130. Avoider()
  131. rospy.spin()
  132. ```
  133. The next line, `rospy.init_node(NAME, ...)`, is very important as it tells rospy the name of your node -- until rospy has this information, it cannot start communicating with the ROS Master. **NOTE:** the name must be a base name, i.e. it cannot contain any slashes "/".
  134. Instantiate class with `Avioder()`
  135. Give control to ROS with `rospy.spin()`. This will allow the callback to be called whenever new messages come in. If we don't put this line in, then the node will not work, and ROS will not process any messages.