ROS2 basics python struggle in real robot project

Hi the construct team I hope all are fine,

I am a beginner in Ros2 and I am struggled for more than 1 week working on the real robot project part 1 the wall following behavior I wrote my code and I am sure that it is correct but it dose not work so I would appreciate if you can tell me where is the mistake or what should I do if my code is not correct.

this is the code of :

import rclpy
from rclpy.node import Node
from sensor_msgs.msg import LaserScan
from geometry_msgs.msg import Twist

class WallFollower(Node):
    def __init__(self):
        self.publisher_ = self.create_publisher(Twist, '/cmd_vel', 10)
        self.subscription_ = self.create_subscription(
        self.wall_distance_ = 0.3
        self.front_wall_distance_ = 0.5

    def laser_callback(self, msg):
        ranges = msg.ranges
        right_ray_index = int(len(ranges) * 3 / 4)  # Index of the rightmost laser ray
        front_ray_index = int(len(ranges) / 2)  # Index of the laser ray in front of the robot

        # Check if there is a wall in front
        if ranges[front_ray_index] < self.front_wall_distance_:
            self.update_velocity(0.0, 0.45)  # Turn fast to the left

        # Calculate the distance to the wall on the right
        right_distance = ranges[right_ray_index]

        # Adjust the linear and angular velocities based on the distance to the wall
        if right_distance > self.wall_distance_ + 0.05:
            self.update_velocity(0.15, -0.45)  # Approach the wall
        elif right_distance < self.wall_distance_ - 0.05:
            self.update_velocity(0.15, 0.45)  # Move away from the wall
            self.update_velocity(0.15, 0.0)  # Maintain the current distance

    def update_velocity(self, linear, angular):
        # Create a Twist message with the provided linear and angular velocities
        msg = Twist()
        msg.linear.x = linear
        msg.angular.z = angular

def main(args=None):
    wall_follower = WallFollower()

if __name__ == '__main__':

I will appreciate your help :blush:

Best Regards,


My problem is solved it was that the front laser readings was not reading so I solve the issue

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.