1

How does one add a random DELAY between 10 and 20 seconds?

For example in the following stepper logic I have a delay of 11 seconds - expressed in milliseconds as: delay(11000).

What would I need to add (or modify) so this is randomized between 10 and 20 seconds?

//#define IN1 8
//#define IN2 9
//#define IN3 10
//#define IN4 11
int Steps = 0;
boolean Direction = true;
unsigned long last_time;
unsigned long currentMillis ;
int steps_left=4095;
long time;
void setup()
{
Serial.begin(115200);
pinMode(IN1, OUTPUT); 
pinMode(IN2, OUTPUT); 
pinMode(IN3, OUTPUT); 
pinMode(IN4, OUTPUT); 
}
void loop()
{
 while(steps_left>0){
 currentMillis = micros();
 if(currentMillis-last_time>=1000){
 stepper(1); 
 time=time+micros()-last_time;
 last_time=micros();
 steps_left--;
 }
 }
 Serial.println(time);
 Serial.println("Wait...!");
 delay(11000); // delay timing
 Direction=!Direction;
 steps_left=4095;
}

Forgive the appearance of the code. Everytime I post it gets butchered. Hopefully it's understandable.

Juraj
18.3k4 gold badges31 silver badges49 bronze badges
asked Sep 4, 2018 at 17:46
1

1 Answer 1

4

In setup(), add

randomSeed(analogRead(0));

This reads the value of an analog input pin, which if not connected, will float to relatively random values between 0 and 1023. This "seeds" the random number generator so the pattern of random numbers you will get later doesn't always give the same results each time you start the sketch.

In your delay() call, just replace the fixed value with a call to the random(min, max) function, as:

delay(random(10000, 20000));
answered Sep 4, 2018 at 18:04
2
  • 1
    But during debug, consider using a constant seed so you can make repeatable results or inspect the result of a single change. Commented Sep 4, 2018 at 19:24
  • Hey thanks so much you guys. Much appreciated. I'm learning as I go and this is a big help! Commented Sep 5, 2018 at 0:35

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.