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.
-
arduino.cc/reference/en/language/functions/random-numbers/…Juraj– Juraj ♦2018年09月04日 17:59:53 +00:00Commented Sep 4, 2018 at 17:59
1 Answer 1
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));
-
1But during debug, consider using a constant seed so you can make repeatable results or inspect the result of a single change.JRobert– JRobert2018年09月04日 19:24:39 +00:00Commented 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– ebucket2018年09月05日 00:35:31 +00:00Commented Sep 5, 2018 at 0:35