Hey guys this is a servo code I was given to work with from the help of this board.
Basically it’s purpose is to turn the servo 180 degrees when there is an input in pin 7, and back to 0 degrees when the input is zero. The servo is connected to pin 9.
The problem I am facing is that the it does not work all the time. Sometimes it works well, but sometimes it doesn’t do it at all, and there is almost always a HUGE delay after the input in pin 7 is switched between 1 or 0. Like it takes 20-30 seconds before it changes.
This is the code. Is it too complicated?
int pos = 0; // variable to store the servo position
Serial.begin(9600); //start a serial port 9600 for debugging
pinMode(7, INPUT); //make pin 7 our input. This is port will determines power input or no power input (1 or 0)
Serial.println(digitalRead(7)); //print the value from pin 7 to the serial monitor
if(digitalRead(7) == 1) //if the value of pin 7 is equal to 1 (power is applied)
myservo.attach(9); //attach the servo to pin 9
while(pos < 180 && digitalRead(7) == 1) // while’pos’ is less than 180 AND pin 9 still equals 1
myservo.write(pos); // tell servo to go to position in variable ‘pos’
delay(15); // waits 15ms for the servo to reach the position
pos += 1 ; //add 1 to ‘pos’
myservo.detach(); //stop the servo