Now you will put sensing, thinking and acting together in one program.
Every microcontroller program has two parts. Setup runs once when the robot switches on: it tells the board which pins are connected to sensors and which to motors. The loop runs again and again, many times every second, and this is where the robot senses, thinks and acts.
A simple obstacle-avoiding robot works like this: 1. Read the distance sensor. 2. If the distance is more than 20 cm, drive forward. 3. Otherwise stop, back up a little, and turn. 4. Go back to step 1.
Steps 2 and 3 are a decision, written with an if statement. This is the "think" part of the robot.
Test in small steps. First print the sensor readings to your computer and check they make sense. Then test the motors on their own. Only then combine them. When something goes wrong, you will know which part to look at.
Try it: change the 20 cm threshold. What happens at 10 cm? At 40 cm? Which value works best in your room, and why?