for (analogRead (IRpin) == 0 ; analogRead (IRpin)<= 299; pos +=1)
The first part of the for loop is an assignment section. You are not assigning anything. Your loop will compare the value of analogRead() to 0. Regardless of whether it is true or false, the loop will execute.
The second part defines the while part of the loop. The loop executes as long as the while part is true.
The third part defines what happens at the end of the loop. In this case pos is incremented.
You are breaking out of the inner for loop when pos gets to 180, if the sensor reading is 300 or greater.
I don't think that is even close to good code.
What you should do is something like this:
unsigned long lastMove = 0;
int pos = 0;
int dir = 1;
int sensVal = analogRead(IRpin);
if(sensVal < 300 || sensVal > 500) // Nothing is in range, so move the servo
unsigned long currTime = millis();
if(currTime - lastMove > 100) // 100 milliseconds between moves
if(dir > 0)
if(pos < 180)
dir = -1;
if(pos > 0)
dir = 1;
lastMove = currTime;
This tests that there is nothing in the desired range of the sensor. If there is, nothing happens.
If there isn't, it tests that it is time to move the servo. If it isn't, nothing happens. If it is, the position is incremented if is is less than 180 and incrementing. Otherwise it is decremented, if it is greater than 0. Then, the servo is moved to that position, and the time of the move is recorded.