Im currently moving a servo from one side to another by using the typical for loop like this:
int lightON = 180;
int lightOFF = 90;
if (buttonState == HIGH) {
digitalWrite(LED, HIGH);
for (pos1 = lightOFF; pos1 <= lightON; pos1 += 1) {
servo1.write(pos1);
delay(15);
}
digitalWrite(LED, LOW);
}
That would be moving the servo one way and if I push the button again the servo would move another way.
if (buttonState == LOW) {
digitalWrite(LED, HIGH);
for (pos1 = lightON; pos1 >= lightOFF; pos1 -= 1) {
servo1.write(pos1);
delay(15);
}
digitalWrite(LED, LOW);
}
The thing is, I have this very same code in 3 other servos and I don't want to be repeating the same code with 2 different variables (pos and servo) over and over again, so I tried
void runServoLight(int pos, int light1, int light2, Servo servo, int state) {
if (state == 1) {
digitalWrite(LED, HIGH);
for (pos = light1; pos <= light2; pos += 1) {
servo.write(pos);
delay(15);
}
digitalWrite(LED, LOW);
} else if (state == 0) {
digitalWrite(LED, HIGH);
for (pos = light2; pos >= light1; pos -= 1) {
servo.write(pos);
delay(15);
}
digitalWrite(LED, LOW);
}
}
Now instead of running the whole for loop code I only run:
runServoLight(pos1, lightON, lightOFF, servo1, 1);
The problem is that it doesn't seem to work and I can understand why, I may be writing the function wrong but im nor really sure. I would really appreciate some help. Thank you!
light1
needs to be lower thanlight2
. Looks like you got those mixed up in the call. – Mat Nov 30 '20 at 7:21