How to run for loop for given amount of time

Hi Guys, i am new to this, i am writing code for 2 servos , i want servo 1 to move from 40 to 90 degree for 3 mins & once that is done i want Servo 2 to move from 90 to 140 degree for 2 mins.

i want to know how can i set time for 1st servo to run for 3 mins & 2nd servo to run for 2 mins.

here is my code .

#include <Servo.h>
Servo servo1;
Servo servo2;

int pos1 = 40;
int pos2 = 90;

void setup() {
servo1.attach(3);
servo2.attach(5);

}
void loop() {
for (pos1 = 40; pos1 < 90; pos1++)
{
servo1.write(pos1);
delay(40);
}
for (pos1 = 90; pos1 > 40; pos1--)
{
servo1.write(pos1);
delay(40);
}
delay(5000); // 5 second delay between Servo 1 & Servo2
for (pos2 = 90; pos2 < 140; pos2++)
{
servo2.write(pos2);
delay(40);
}
for (pos2 = 140; pos2 > 90; pos2--)
{
servo2.write(pos2);
delay(40);
}
}

You need to respect the forum rules if you want help.

Your question has nothing to do with command line tools. If you had read the sticky post at the top of the forum section, you would have posted your question in a more appropriate section.

You should have used code tags when posting your code. If you had read the forum guide, you would have known this.

I have moved your topic to a more appropriate section. Please edit your post and add those code tags.

1 Like

Do you want servo 1 to cycle forth and back for 3 minutes or do you want it to cycle just once taking 3 minutes to do so?

Same question for servo 2.

Either way what you need are 2 Boolean flags to indicate the stage of the sequence you are in.

In your declarations add:

bool servo1Done=FALSE;
bool servo2Done=FALSE;

Then in the loop you will need some conditional executions based on those flags:


if servo1Done == FALSE {

  Put servo1 activities here. When done you will execute this line:

  servo1Done=TRUE;

  }

if servo1Done == TRUE && servo2Done == FALSE {.   // added “servo1Done == true && “ part

  Put servo2 activities here. When done you will execute this line:

  servo2Done=TRUE;

  }

This is a rough outline of additions to your sketch. There are other ways to do this, such as a state machine. This is just one suggestion to get you thinking along a path.

1 Like

look this over

#include <Servo.h>
Servo servo1;
Servo servo2;

const int PosA = 40;
const int PosB = 90;

int  dir1 =  1;
int  pos1 = PosA;
unsigned long msec1 = 3000;

int  dir2 = -1;
int  pos2 = PosB;
unsigned long msec2 = 2000;

const unsigned long MsecAdv   = 40;
      unsigned long msecLst;

// -----------------------------------------------------------------------------
void
advServo (
    Servo  servo,
    int   &pos,
    int   &dir )
{
    pos1 += dir;
    if (PosA >= pos || PosB <= pos)
        dir = -dir;         // reverse direction at end-points

    servo1.write (pos);
    Serial.println (pos);
}

// -----------------------------------------------------------------------------
void loop ()
{
    unsigned long msec = millis ();

    if (msec - msecLst >= MsecAdv)  {   // do something every MsecAdv msec
        msecLst += MsecAdv;             // update timestamp

        if (msec1 > 0)  {       // do somethign for 
            msec1 -= MsecAdv;           // decrement run time for servo 1
            Serial.print (" msec ");
            Serial.print (msec);
            Serial.print ("  run1 ");
            advServo (servo1, pos1, dir1);
        }
        else if (msec2 > 0)  {
            msec2 -= MsecAdv;           // decrement run time for servo 2
            Serial.print (" msec ");
            Serial.print (msec);
            Serial.print ("  run2 ");
            advServo (servo2, pos2, dir2);
        }
    }
}

// -----------------------------------------------------------------------------
void setup ()
{
    Serial.begin (9600);
    servo1.attach (3);
    servo2.attach (5);
}

Hello abhiyantriki

What is the task of this sketch in real life?

Are you sure that the name is servo1 ?

There are four positions

I can see only

const int PosA = 40;
const int PosB = 90;

you're right.

but this approach can easily handle the fixes: both servos and positions

Those are (3, 2) seconds, not minutes.

Sweep Servo1 from 40 to 90 over three minutes and stop.
Sweep Servo2 from 90 to 140 over two minutes and stop.

#include <Servo.h>
Servo servo1;
Servo servo2;

int pos1 = 40, pos2 = 90, pos3 = 140, servoDegree1 = pos1, servoDegree2 = pos2;

int sweepDegree1 = 90 - 40; // 50 degrees
unsigned long timer1;
unsigned long sweepTime1 = 3 * 60 * 1000UL; // 3 minutes
unsigned long interval1 = sweepTime1 / sweepDegree1; // 3600ms per degree

int sweepDegree2 = 140 - 90; // 60 degrees
unsigned long timer2;
unsigned long sweepTime2 = 2 * 60 * 1000UL; // 2 minutes
unsigned long interval2 = sweepTime2 / sweepDegree2; // time / degree = 2400ms per degree

void setup() {
  Serial.begin(115200);
  servo1.attach(3);
  servo2.attach(5);
  servo1.write(pos1); // start position
  servo2.write(pos2); // start position
  printout(pos1, pos2);
}

void loop() {
  // servo1 time window
  if (millis() >= 0 && millis() < 180000) { // 0 to 3 minutes
    // move servo1
    if (millis() - timer1 > interval1) {
      timer1 = millis();
      servoDegree1++;
      printout(servoDegree1, servoDegree2);
      if (servoDegree1 > pos2)
        servoDegree1 = pos1;
      servo1.write(servoDegree1);
    }
  }

  // servo2 time window
  if (millis() > 180000 && millis() < 300000) // 3 to 5 minutes
    // move servo2
    if (millis() - timer2 > interval2) {
      timer2 = millis();
      servoDegree2++;
      printout(servoDegree1, servoDegree2);
      if (servoDegree2 > pos3)
        servoDegree2 = pos2;
      servo2.write(servoDegree2);
    }
}

// Serial Monitor display: time, servo1, servo2
void printout(int sd1, int sd2) {
  Serial.print("Time: ");

  unsigned long seconds = millis() / 1000UL;
  if (seconds < 100) Serial.print(" ");
  if (seconds < 10) Serial.print(" ");

  Serial.print(seconds);
  Serial.print("s Servo1 ");
  if (sd1 < 100) Serial.print(" ");
  if (sd1 < 10) Serial.print(" ");
  Serial.print(sd1);
  Serial.print("°");

  Serial.print(" Servo2 ");
  if (sd2 < 100) Serial.print(" ");
  if (sd2 < 10) Serial.print(" ");
  Serial.print(sd2);
  Serial.println("°");
}
click for wokwi.com diagram.json
{
  "version": 1,
  "author": "Anonymous maker",
  "editor": "wokwi",
  "parts": [
    { "type": "wokwi-arduino-nano", "id": "nano", "top": 4.8, "left": -10.1, "attrs": {} },
    { "type": "wokwi-servo", "id": "servo1", "top": -78.8, "left": 172.8, "attrs": {} },
    { "type": "wokwi-servo", "id": "servo2", "top": -165.2, "left": 172.8, "attrs": {} },
    { "type": "wokwi-vcc", "id": "vcc1", "top": -162.44, "left": 144, "attrs": {} },
    { "type": "wokwi-gnd", "id": "gnd1", "top": 86.4, "left": 153, "attrs": {} }
  ],
  "connections": [
    [ "nano:3", "servo1:PWM", "green", [ "v0" ] ],
    [ "nano:5", "servo2:PWM", "green", [ "v0" ] ],
    [ "gnd1:GND", "servo1:GND", "black", [ "v0" ] ],
    [ "gnd1:GND", "servo2:GND", "black", [ "v0" ] ],
    [ "gnd1:GND", "nano:GND.1", "black", [ "v-9.6", "h-28.8" ] ],
    [ "vcc1:VCC", "servo2:V+", "red", [ "v0" ] ],
    [ "vcc1:VCC", "servo1:V+", "red", [ "v0" ] ]
  ],
  "dependencies": {}
}

much easier to test the logic using those values

OP is free to change them

1 Like

They are 3, 2 seconds when used with millis() function -- am I correct? Otherwise, the unit/dimension of 3000 in this dclaration: unsigned long msec1 = 3000; could be anything -- cm/inch/m3.

So true. I spent thirty minutes waiting for "5min" time to elapse (post #9) while fixing my errors (still have one).

1 Like

Two days of questions and suggestions and no reply from @abhiyantriki , the OP. Are we wasting our time?

Not I.