Random Number generation between range

Hi everyone.

I’m looking for the spark equivalent of rand/random().

I notice that the web IDE recognises the keyword rand() but I’m looking to specify the range of numbers to select from.
I am trying to get a random number between 0 and 9.

The compiler doesn’t like rand(0,9) or random(0,9) and reports too many arguments error.
Similarly, I tried rand(9) assuming the minimum bound defaults to 0. Same error.

Any clues?

Thanks in advanced.
Joni

HI Joni,

I have been using the following for now. Gives random between 1 and maxRand. Remove the +1 for 0 to maxRand.

int random(int maxRand)
{
    return rand() % maxRand + 1;
}

Txs
Chris

3 Likes

I did quick fact check with previous post, but didn’t notice Google gave me GCC Fortran page instead of GCC C++. I have used so many languages I always mix details if I haven’t coded for a while. :confused:

If you like to extend @Kitard’s function with minimum value, it should be:

int random(int minRand, int maxRand)
{
return rand() % (maxRand-minRand+1) + minRand;
}

The result includes both minRand and maxRand. If Spark supports full C++, you should be able to include both 1- and 2-argument versions if you like.

1 Like

I created a full example if anyone needs something like this:

#include "application.h"

// Uncomment for faster debugging!
//#include "spark_disable_wlan.h"

int random(int maxVal);
int random(int minVal, int maxVal);

// returns a random integar between 0 and maxVal
int random(int maxVal)
{
  return random( 0, maxVal);
}

// returns a random integar between minVal and maxVal
int random(int minVal, int maxVal)
{
  // int rand(void); included by default from newlib
  return rand() % (maxVal-minVal+1) + minVal;
}

void setup(void) {
  Serial.begin(115200); // Make sure your serial terminal is closed before power the Core.
  while(!Serial.available()) { // Open serial terminal and Press ENTER.
    #ifdef SPARK_WLAN_SETUP
      SPARK_WLAN_Loop(); 
    #endif
  }

  // Waiting for a human to start the program at a random time...
  // humans are so very random :P
  uint32_t seed = millis(); 
  srand(seed); // void srand(unsigned int seed);
}

void loop() {
  // Generate a random number, from 1 - 10.
  int random_num = random(1,10);

  // Generate a random number, from 0 - 10.
  //int random_num = random(10);

  char bar[10] = "";
  int random_copy = random_num;
  while(random_copy > 0) {
    strcat(bar,"="); // Create a bargraph
    random_copy--;
  }

  // Scroll our bargraph in the serial terminal
  Serial.print(bar);
  Serial.print(" ");
  Serial.println( random_num ); 
  delay(100);
}
2 Likes

Thank you man, this worked for me!

Just an update, now this is also supported for anyone who has the same question but wants a single command line
MyRandNumber = random(0,7); //picks number between 0 and 7

Errr (Correction)
MyRandNumber = random(0,7); //picks number between 0 and 6