Timer that activates Random(); run again without delaying Switch, help

So I merged a timer with a random the best i could and came up with this idea. It works as expected timer every second causes a int to change and activates a case to print a word. I want it to activate a switch and continue to repeat over and over until random is changed again and activating another switch case.

int initialTime;
int interval = 1000;

void setup()
{
  initialTime = millis();
}

void draw()
{
   String[] num = { "0", "1", "2","3"};

  // if current time minus lastStored bigger than interval 
  if (millis() - initialTime > interval){

      int index = int(random(num.length));  // Same as int(random(4))
          // reset counter
    initialTime = millis();
        switch(index) 
              {
              case 0: 
                println("Zero");  // Does not execute
                break;
              case 1: 
                println("One");  // Prints "One"
                break;
                  case 2: 
                println("two");  // Prints "two"
                break;
                  case 3: 
                println("three");  // Prints "three"
                break;
              }

  }
}

Answers

  • _vk_vk
    edited July 2014 Answer ✓

    The switch should be outside the timer i think, look, is that so?

    int initialTime;
    int interval = 1000;
    int index ;
    
    void setup(){
      index = int(random(4));
      initialTime = millis();
    
    }
    
    void draw(){
    
    
      // if current time minus lastStored bigger than interval 
      if (millis() - initialTime > interval) {
    
        index = int(random(4));  // As num was unused... 
        // reset counter
        initialTime = millis();
        println("one sec passed... new index is: " + index);
      }
      switch(index) 
      {
      case 0: 
        println("Zero");  // Does not execute
        break;
      case 1: 
        println("One");  // Prints "One"
        break;
      case 2: 
        println("two");  // Prints "two"
        break;
      case 3: 
        println("three");  // Prints "three"
        break;
      }
    }
    
  • I want it to activate a switch and continue to repeat over and over until random is changed again and activating another switch case.

    Can't figure out what you want to. But I guess if you wanna the switch to continue repeating,
    you should place it outside the if block!

  • Thank You _vk I didn't think of using "index = int(4);" in setup. I was trying outside of the if and int index on top and so forth and I could never get it to work and so my overall project progresses to nearly being completed after i integrated this example into it.

  • ops, was meant to be index = int(random(4)); corrected above ; )

Sign In or Register to comment.