Solutions




spin_in_circles.py

#!/usr/bin/env python3
          
          import rclpy
          from rclpy.node import Node
          from geometry_msgs.msg import Twist

          class SpinCircles(Node):

              def __init__(self):
                  super().__init__('spin_circles')
                  self.publisher_ = self.create_publisher(Twist, '/turtle1/cmd_vel', 10)
                  timer_period = 0.5  # seconds
                  self.timer = self.create_timer(timer_period, self.timer_callback)

              def timer_callback(self):
                  vel = Twist()
                  vel.linear.x=1.0
                  vel.angular.z=0.9
                  self.publisher_.publish(vel)
                  self.get_logger().info('Publishing: x"%f"' % vel.linear.x)
                  self.get_logger().info('Publishing: z"%f"' % vel.angular.z)


          def main(args=None):
              rclpy.init(args=args)
              pc_publisher = SpinCircles()
              rclpy.spin(pc_publisher)
              pc_publisher.destroy_node()
              rclpy.shutdown()


          if __name__ == '__main__':
              main()

stop_at_wall.py

#!/usr/bin/env python3
​
import rclpy
from rclpy.node import Node
from geometry_msgs.msg import Twist

# msgs needed for /cmd_vel
from geometry_msgs.msg import Twist, Vector3

from sensor_msgs.msg import LaserScan

# How close we will get to wall.
distance = 1

class StopAtWall(Node):

    def __init__(self):
        super().__init__('walk_to_wall')
        
        # Create a default twist msg (all values 0).
        lin = Vector3()
        ang = Vector3()
        self.twist = Twist(linear=lin,angular=ang)

        # Publish msg to cmd_vel.
        self.publisher_ = self.create_publisher(
                Twist,      # message type
                '/demo/cmd_demo',  # topic name
                10)          # history depth
        
        self.sub_lidar = self.create_subscription(
                LaserScan,
                '/scan',
                self.scan_callback,  # function to run upon message arrival
                10)  # allows packet loss

    def scan_callback(self,data):
        self.get_logger().info("StopAtWall heard: {}".format(data.ranges[0]))
        if data.ranges[0] >= distance:
            # Go forward if not close enough to wall.
            self.twist.linear.x = 0.5
            self.get_logger().info("Go baby".format(data.ranges[0]))
        else:
            # Close enough to wall, stop.
            self.twist.linear.x = 0.0
            self.get_logger().info("STOP baby".format(data.ranges[0]))
        self.publisher_.publish(self.twist)

def main(args=None):
    rclpy.init(args=args)
    pc_publisher = StopAtWall()
    rclpy.spin(pc_publisher)
    pc_publisher.destroy_node()
    rclpy.shutdown()


if __name__ == '__main__':
    main()