Micro Servo+ Arduino

When I press the button, the servo keeps running..., but if I press again, it will still run one time of the loop.
Have a look the " Video "
I don't know what's going on.
Can anyone help me??

My code is in below.

Thanks!

#include <Servo.h> 

int buttonPin = 9;  
int servoPin = 8;
int buttonState;

Servo myservo;  

int pos = 0;   

void setup() 
{ 
  myservo.attach(servoPin); 
  pinMode(buttonPin, INPUT);
} 

void loop() 
{ 
  int counter=0;
  buttonState = digitalRead(buttonPin);
  
  if (buttonState == HIGH){
    counter=1;
  }
  
  if(counter==1){
    
    for (pos = 0; pos <= 180; pos += 1) {
      // in steps of 1 degree
      myservo.write(pos);           
      delay(5);                    
    }
    for (pos = 180; pos >= 0; pos -= 1) { 
      myservo.write(pos);           
      delay(5);                     
    }
  }
}

How IS the switch wired? How is the servo powered?

  int counter=0;
  buttonState = digitalRead(buttonPin);
 
  if (buttonState == HIGH){
    counter=1;
  }

That's a lot of code to set counter to the output of the digitalRead() function.

  int counter = digitalRead(buttonPin);

Neither buttonState OR counter are needed.

   if(digitalRead(buttonPin) == HIGH)
   {
      // wave the servo stupidly
   }

Sorry, the video URL was wrong. Now, it is the right one. VIDEO

and the switch is wired like this.

servo is powered Arduino from the 5v pin.

servo is powered Arduino from the 5v pin.

Stop doing that. Servos often require more current than the Arduino can provide.

PaulS:
Stop doing that. Servos often require more current than the Arduino can provide.

Doesn't that depend on the amount of torque required by the application? :slight_smile:

Danois90:
Doesn't that depend on the amount of torque required by the application? :slight_smile:

No. It depends on the amount of current the servo draws. Which may be related to torque, but not directly.