About looping an action for certain time

I am new to coding, I am writing a simple code for running the stepper motor, where I need to control the motor speed with the data from the array. However, I want to loop the action for a certain period of time ( like 1 minute) for each array data, I try to add a while loop in side the for loop, and it just stuck at the action of the first array data. Can anyone help to see which part I am doing wrong, many thanks.

#include <Stepper.h>
int numberofstep=2048;
Stepper motor(numberofstep, 8, 10, 9, 11);

float myarray[] = {1, 0.2, 0.8, 0.2};

unsigned long startMillis;
unsigned long currentMillis;
const unsigned long period = 5000;

void setup()
{ startMillis = millis();}

void loop() {

for (int i=0; i<4; i++)

{ currentMillis = millis();
while ((currentMillis - startMillis) <= period){
motor.setSpeed(16myarray[i]);
motor.step(100);
motor.setSpeed(14
myarray[i]);
motor.step(-100);
delay(100);}
}
}

currentMillis is not updated in the while loop. Perhaps try:

while ((millis() - startMillis) <= period) {

what @jfjlaros said, plus

setSpeed() take an unsigned long as a parameter not a float.

Thanks.

After correct to your suggestion
The motor can stop after 5 seconds, however, it didn't continue the for the 'for loop'.

I am not quite sure what this means, but I presume you want to run the while loop four times. In that case, you might want to change this line,

to:

startMillis = millis();

the .step() function only takes a defined number of steps and then stops. It has nothing to do with time based movement like running for 1 minutes or something

Thank you so much~!!!
It is working now~!!! ~

below is the update one~~~

#include <Stepper.h>
int numberofstep=2048;
Stepper motor(numberofstep, 8, 10, 9, 11);
float myarray[] = {1, 0.4, 0.5, 0.1};
unsigned long startMillis;
const unsigned long period = 1000;

void setup()
{

}
void loop() {

for (int i=0; i<4; i++)

{ startMillis = millis();
while ((millis() - startMillis) <= period){
motor.setSpeed(16myarray[i]);
motor.step(100);
motor.setSpeed(14
myarray[i]);
motor.step(-100);
delay(100);}
}}

Good to hear.

Can you please mark the most helpful post as the solution? This prevents helpers spending time on a solved issue and it will lead people with the same question to the correct answer directly.

And while you are at it, you may want to read the guidelines regarding code tags.

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