Using a random delay with millis between two times

I want to control a device at random off and on intervals, each state random between 1 and 4 seconds, Not less than 1. How do I say that in this code?

const int smokeMachine = 6;
int endTime = 0;
int state = 0;

void setup() {
  pinMode(smokeMachine, OUTPUT);
  randomSeed(analogRead(0));
}

void loop() {
  static int interval = random(4000);

  //Turn Smoke ON
  if (millis() - endTime > interval and state == 0) {
    digitalWrite(smokeMachine, HIGH);

    endTime = millis();
    state = 1;
  }

  
  //Turn Smoke OFF
  if (millis() - endTime > interval and state == 1) {
    digitalWrite(smokeMachine, LOW);
    endTime = millis();
    state = 0;
    interval = random(4000);
  }
}

Just a glance now from under the umbrella.

random() can take two arguments, so

    interval = random(1000, 4001);

would set interval to a number between 1000 and 4000 inclusive.

a7

1 Like

Awesome. Thanks!

And for anyone following along or future reference, if random() didn't have a range, you could write

    interval = 1000 + random(3001);

which would do the same thing.

a7

So, I finally got around to trying this out. It seems to work a few times, then just stops. Any ideas why?

const int smokeMachine = 3;
int endTime = 0;
int state = 0;

void setup() {
  pinMode(smokeMachine, OUTPUT);
  randomSeed(analogRead(0));
}

void loop() {
  static int interval = random(3000, 7001);

  //Turn Smoke ON
  if (millis() - endTime > interval and state == 0) {
    digitalWrite(smokeMachine, HIGH);

    endTime = millis();
    state = 1;
  }

  
  //Turn Smoke OFF
  if (millis() - endTime > interval and state == 1) {
    digitalWrite(smokeMachine, LOW);
    endTime = millis();
    state = 0;
    interval = random(1000, 2001);
  }
}

Hello highlandranger

Did you check the compiler warnings?

There weren't any?

How are you powering your device - you must not take significant power ( few mA) from the Arduino or you will over heat the regulator causing the board to shutdown.

There weren't any if you didn't get any.

You should see them in red ink in the output window of the sketch window in the IDE. If there are none, it may be because by default the IDE does not bother you with them.

Go to the IDE preferences, choose verbose output during compiling and dial up the warnings to all.

I fixed the problems the compiler warning brought to my attention, that I had seen, natuarlly :wink:

If you do the same it should help.

Before you fix your code, time how long it is before it jams.

After you fix your code, if it still jams, time how long before it jams.

a7

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