Problem with random()

Why does this not work? When it runs only the first value in the call is observed, so every 2.5 seconds it validates TRUE instead of something random between 2.5 and 10 seconcds.

lastPulseAt = 0;

void setup() {
    blah blah
}

void loop() {
    int randPulse = random(2500,10000);
    if (millis() - lastPulseAt > randPulse) {
      lastPulseAt = millis();
      digitalWrite(24, HIGH);
      delay(10);
      digitalWrite(24, LOW);
    }
}

That's because you create a new random value between 2500 and 10000 for randPulse on each iteration of the loop() method.

Once you've crossed the 2500 millisecond threshold, chances are very good that one of the next few thousand random() calls within the next few milliseconds will produce 2500 or something close to it, causing your if block to be executed.

Set randPulse inside the if block, not every time loop() executes.

In addition, randPulse will have to be global or static.

Works but you probably want this :

unsigned long lastPulseAt = 0;
int randPulse;

void setup() 
{
  Serial.begin(115200);
  Serial.println("Start ");
  pinMode(13, OUTPUT);  // may be pin 24 too
}

void loop() 
{
  Serial.println(randPulse);
  if (millis() - lastPulseAt > randPulse) 
  {
    lastPulseAt = millis();
    digitalWrite(13, HIGH);
    delay(10);
    digitalWrite(13, LOW);
    randPulse = random(2500,10000);
  }
}

Works after the suggestions. Thanks. here's where I ended up.

unsigned long lastPulseAt = 0;
int randPulse = 0;

void setup() {
    blah blah
}

void loop() {
   if (millis() - lastPulseAt > randPulse) {
      lastPulseAt = millis();
      randPulse = random(2500,10000);
      digitalWrite(24, HIGH);
      delay(10);
      digitalWrite(24, LOW);
    }
}

Really? - the blah blah compiles for you? :slight_smile: