Some Code to Start you off on Day 4
Wall Approach Starter
This code sets up a basic run loop, a velocity publisher, and a subscription to the laser scan data.
Source: wall_approach_starter.py
""" This node uses the laser scan measurement pointing straight ahead from
the robot and compares it to a desired set distance. The forward velocity
of the robot is adjusted until the robot achieves the desired distance """
import rclpy
from rclpy.node import Node
from sensor_msgs.msg import LaserScan
from geometry_msgs.msg import Twist
from rclpy.parameter import Parameter
from rcl_interfaces.msg import SetParametersResult
from rclpy.qos import qos_profile_sensor_data
class WallApproachNode(Node):
""" This class wraps the basic functionality of the node """
def __init__(self):
super().__init__('wall_approach')
# the run_loop adjusts the robot's velocity based on latest laser data
self.create_timer(0.1, self.run_loop)
self.create_subscription(LaserScan, 'scan', self.process_scan, qos_profile=qos_profile_sensor_data)
self.vel_pub = self.create_publisher(Twist, 'cmd_vel', 10)
# distance_to_obstacle is used to communciate laser data to run_loop
self.distance_to_obstacle = None
# Kp is the constant or to apply to the proportional error signal
self.Kp = 0.4
# target_distance is the desired distance to the obstacle in front
self.target_distance = 1.2
def run_loop(self):
msg = Twist()
# Your logic here!
self.vel_pub.publish(msg)
def process_scan(self, msg):
if msg.ranges[0] != 0.0:
# checking for the value 0.0 ensures the data is valid.
# Your logic here!
print('scan received', msg.ranges[0])
def main(args=None):
rclpy.init(args=args)
node = WallApproachNode()
rclpy.spin(node)
rclpy.shutdown()
if __name__ == '__main__':
main()