Je bent al een goed stuk op weg.
De loop kan echter een stuk eenvoudiger en zal je de mogelijkheid geven te reageren op obstakels. Je hoeft echt geen loop in de loop te maken.
int step = 1;
int position = 0;
int distance = 0;
void loop()
{
position = position + step;
//set the servo to the new position
myservo.write(pos);
//read the distance sensor - create this method yourself
distance = ReadTheSensor();
//move the robot depending on the distance and the direction we measured it - create this method yourself
DoSomethingWithTheMotorsSoWeMove(distance, pos);
delay(10);
//switch directions on extremes
if (position == 180) step = -1;
if (position == 0) step = 1;
}
HTH
Edit by jantje: added code tags