0
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 <= 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 >= 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.

1
  • Does it work if you extract the code from the function? Commented Dec 24, 2015 at 23:24

1 Answer 1

2

Arrange your code like this:

Servo servo1, servo2;

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

void loop()
{
    int pos;

    for (pos = 0; pos <= 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.

2
  • It would be helpful to briefly describe what is significant about the difference in the arrangement. Commented Dec 31, 2015 at 17:47
  • I thought the code was short enough so that the difference is obvious. But I will update my answer next year. Commented Dec 31, 2015 at 18:20

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.