PeterH:
The code you've posted ought to work OK the very first time the button goes HIGH after a reset, but after that you're going to hit various bugs.The most likely reason for the big delay you mention is that you have already pressed the button previously and the sketch is still trying to sweep the servo from the previous operation. The bugs in it will stop that doing anything useful most of the time, but it will still keep the sketch busy and stop it detecting further inputs for a long time.
Do you specifically want to move the servo slowly?
Do you really need to detach the servo when it has reached the end position, and if so why?
Your code to return the servo to zero degrees is missing.
I want it to open and close quickly.
No I guess I don't need it to detach.
and here is the full code lol sorry didn't put the whole thing up
#include <Servo.h>
Servo myservo;
int pos = 0; // variable to store the servo position
void setup()
{
Serial.begin(9600); //start a serial port 9600 for debugging
pinMode(7, INPUT); //make pin 9 our input. This is port will determines power input or no power input (1 or 0)
}
void loop()
{
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
}
else if(digitalRead(7) == 0) //else if pin 7 is equal to 0 (power is not applied)
{
myservo.attach(9); //re-attach the servo to pin 9
while(pos > 0 || pos < 5 && digitalRead(7) == 0) //while 'pos' is greater than zero OR less than 5 AND pin 7 still equals 0
{
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; //subtract 1 from 'pos'
}
myservo.detach(); //stop the servo
}
}