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.

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));
2
  • 1
    But during debug, consider using a constant seed so you can make repeatable results or inspect the result of a single change.
    – JRobert
    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!
    – ebucket
    Sep 5, 2018 at 0:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.