Need help using a for loop for servo

Hello! I am trying to get my servo to move back and fourth 180 degrees 6 times. I put a for loop in my void loop section of the code but it seems to just keep going on and on no matter what. Attached below is my code.

#include<Servo.h>// include servo library
Servo myservo1;
Servo myservo2;
int POWERON=6; //switch in position 6 will power on system
int LED=5; //LED is in pin 5

void setup() {
// put your setup code here, to run once:
myservo1.attach(10); //Servo 1 is attached to pin 10
myservo2.attach(9); //Servo 2 is attached to pin 9
pinMode(POWERON,INPUT);
pinMode(POWEROFF,INPUT);
pinMode(LED,OUTPUT);

if(digitalRead(POWERON)==HIGH)
{
digitalWrite(LED,HIGH);
myservo1.write(45);
delay(3000);
myservo1.write(0);
}}

void loop() {
// put your main code here, to run repeatedly:
for (byte times = 0;times < 6; times++)
myservo2.write(0);
delay(500);
myservo2.write(180);
delay(500);
}

That's what loop() does. It loops. If you want something done once and not repeated, put it in setup(). It is OK to have nothing in loop().

I have edited your code a bit. Please have a look.
you can put the code in setup() function which will run only once. The code in the void() function will run forever.

Right after I posted this I realized that was probably the case, having a case of the Mondays I guess. Is the loop format correct for putting it in the setup?

You forgot to put brackets around the body of the loop so it only repeats the first line.

If you auto-indent you'll see how the for loop binds to a single statement. You need braces around the loop body if more than one statement.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.