My main goal for the second demo was to both make the robot walk faster and to make it avoid hitting things in front of it. I added a Reflective Photointerruptor sensor to the front of the robot to detect if there was something in front of it. I used digital read and the threshold it set was perfect to let the robot go right up to the wall without hitting it. The robot will then weight at the walls until the obstacle is moved. The legs do a similar thing, waiting for one leg to complete its motion before starting the other legs motion.

#include <Servo.h&gt; 

Servo myservo;

void setup() 
{ 
    myservo.attach(3);
    pinMode(A0, INPUT);
    Serial.begin(9600);

} 

void loop() {
   myservo.write(179);
    Serial.println(myservo.read());

   while (myservo.read() < 177){
    delay(10);
   }
   myservo.write(135);
   while(myservo.read() &gt; 140){
    delay(10);
   }

   while(digitalRead(A0) == 0){
    delay(5);
   }
 }

https://drive.google.com/drive/folders/1cZJ_AOAwcQpJNZCFMBpMeLT9t8A1rwRj?usp=sharing