Could you tell me what is wrong with this Arduino code? void fn( int pin, int pos)
{
    Servo temp;
    temp.attach(pin);
    temp.write(pos);
    delay(15); 
    temp.detach();
}

void loop()
{
    int pos = 0 ; 
    for (pos = 0; pos &lt;= 180; pos += 1) { // goes from 0 degrees to 180 degrees
        // in steps of 1 degree
        //tmp2.write(pos);
        //delay(15);
        fn(41,pos);
        fn(2,180 - pos);   
    }
    for (pos = 180; pos &gt;= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
        fn(41,pos);
        fn(2,180 - pos);
    }    
}


But when I run the code in mega , the servo does not move when attached to pin 2 or 41. 
The reason I am creating a function fn , is so that the servo does not stay attached. I want the servo to rotate freely when I am not giving it a pwm signal.
Arrange your code like this:

Servo servo1, servo2;

void setup() {
    servo1.attach(41);
    servo2.attach(2);
}

void loop()
{
    int pos;

    for (pos = 0; pos &lt;= 180; pos++) {
        servo1.write(pos);
        delay(15);
        servo2.write(180 - pos);
        delay(15);
    }

    // 2nd loop here

}


It's rather inefficient to detach a servo after each write and then attach it again for the next write. Simply keep it up all the time.