Function calling

Hey, quick question that some googling cant answer it seems. :open_mouth:

When calling a function, is it possible to declare which of two or more variables to use?


int servocontrol(int x){
while(servoSwitchState == 0){
potVal = digitalRead(potPin);
angle = map(potVal, 0, 1023, 0, 179);
myServo'x'.write(angle); <-- this is where I want to make the distinction between myServo1 & myServo2.
if(digitalRead(4) == HIGH){
if(servoSwitchState == 0){
servoSwitchState = 1;
}
else{
servoSwitchState = 0;
}
}
}
}

When calling the function with servocontrol(1) / servocontrol(2).


Possible?

No. Names are long gone by the time code executes. You can pass a pointer to the servo object, though.

Would this work instead? Although a simple if test would work with just two servos, the switch might be better if there's a chance of adding more servos later on. Also, why is the function type specifier int? Nothing is returned from the function call.

int servocontrol(int x)
{
  while (servoSwitchState == 0){
    potVal = digitalRead(potPin);
    angle = map(potVal, 0, 1023, 0, 179);
    switch (x) {
       case 1:
          myServo1.write(angle); 
          break;

       case 2:
          myServo2.write(angle); 
          break;
       default:
          // should never be here...
          break;
    }
   
     if (digitalRead(4) == HIGH) {
       if (servoSwitchState == 0) {
        servoSwitchState = 1;
       } else {
        servoSwitchState = 0;
       }
    }
  }
}

Or an array of Servo objects

econjack:
Also, why is the function type specifier int? Nothing is returned from the function call.

That's because I don't really know what I'm doing. (Changed it to void now) :slight_smile: Alot of trial and error at the moment. Mostly error..

The code seems to work tho, I'll try again tomorrow.