In this case, our robot will move freely in a given space, but as soon as it comes near to an object or an obstacle, it will turn or move backward, thus avoiding the obstacle. In this kind of project, we generally use an ultrasonic sensor. As the robot moves, the ultrasonic sensor keeps measuring the distance it is away from objects. When the sensor detects that the distance value is very low, and the robot may collide with the nearby object, it will command the robot to change direction, thus avoiding the obstacle.
To create an obstacle-avoiding robot, you first need to mount the ultrasonic sensor on the robot. Inside my robotic kit, there is already an attachment that allows me to mount the ultrasonic sensor on the robot. This attachment looks as follows:

After attaching the ultrasonic sensor on the robot, the final assembly looks as follows...