Im currently trying to control 3 servos with the same movements and pretty much the same code, I use a push button and try to use it as a toggle switch:
int lightON = 180;
int lightOFF = 90;
buttonState1 = digitalRead(button1);
if (directionState1 == 0) {
if (buttonState1 == HIGH ) {
directionState1 = 1;
digitalWrite(LED, HIGH);
servo1.attach(D7);
Serial.println("Servo 1 is moving");
for (pos1 = lightOFF; pos1 <= lightON; pos1 += 1) {
servo1.write(pos1);
delay(15);
}
servo1.detach();
digitalWrite(LED, LOW);
}
} else if (directionState1 == 1) {
if (buttonState1 == HIGH) {
directionState1 = 0;
digitalWrite(LED, HIGH);
servo1.attach(D7);
Serial.println("Servo 1 is moving");
for (pos1 = lightON; pos1 >= lightOFF; pos1 -= 1) {
servo1.write(pos1);
delay(15);
}
servo1.detach();
digitalWrite(LED, LOW);
}
}
The thing is, this works but my problem is that I have this repeated over 3 times in my code for 3 other servos and the only things changed are the name of the servo and its position. I decided to try and create a function which will let just write it once and run it every time I press the button. This is what I made.
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);
}
}
The parameters of the function are to control my servos. It doesn’t seem to work and I cant understand why.
This is how it looks now:
buttonState1 = digitalRead(button1);
if (directionState1 == 0) {
if (buttonState1 == HIGH) {
directionState1 = 1;
servo1.attach(D7);
Serial.println("Servo 1 is moving");
runServoLight(pos1, lightON, lightOFF, servo1, 1);
servo1.detach();
}
} else if (directionState1 == 1) {
if (buttonState1 == HIGH) {
directionState1 = 0;
servo1.attach(D7);
Serial.println("Servo Luz 1 en movimiento");
runServoLight(pos1, lightON, lightOFF, servo1, 0);
servo1.detach();
}
}
I don’t understand what is wrong. I would really appreciate some help. English is not my native tongue so apologies if the grammar is not that good.