Randomize string

Okay, so I tried to create a random string generator that will printout 5 random characters with this code.

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
}

void loop() {
  // put your main code here, to run repeatedly:
delay(2000);
GenTxt();
}
void GenTxt(){
  int generated=0;
while (generated<6)
{
   byte randomValue = random(0, 26);
   char letter = randomValue + 'a';
   if(randomValue > 26)
      letter = (randomValue - 26) ;
      Serial.print(letter);
      generated ++;
}
Serial.println("");
}

Then I noticed that this code give's me the same random string every time it restarts.

lrfkqy
uqfjkx
yqvnrt
ysfrzr
mzlygf

everytime arduino starts it will generate same string. Idk what is wrong. Is there any other way to random 5 character string? :confused:

Idk what is wrong

Working as designed. The Arduino generates the same string of "random" numbers when reset. There are ways round this. Take a look at the randomSeed() function which allows you to seed the "random" number generator with a different start position.

One way often cited to randomise the output further is to use the value read from a floating analogue input as the parameter of randomSeed() but its effectiveness is also debated.

One way that I have used to produce a possibly more random value to use with randomSeed() is to wait in a loop for user input and to use the value of millis() at the time of user input as the randomSeed() parameter.

UKHeliBob:
One way that I have used to produce a possibly more random value to use with randomSeed() is to wait in a loop for user input and to use the value of millis() at the time of user input as the randomSeed() parameter.

Thanks, this actually helped me and now I have new idea. God Bless mate ! :slight_smile:

You ask for a value between 0...25 (inclusive)

    byte randomValue = random(0, 26);

so why do you think it will ever be greater than 26?

    if (randomValue > 26)
      letter = (randomValue - 26) ;

This is useless code

You could also use EEPROM to ensure a unique seed after every reset:

#include <EEPROM.h>

#define EEPROM_ADDRESS 0
#define SEED_MULTIPLIER 23

void setup()
{
  unsigned long seed;
  EEPROM.get(EEPROM_ADDRESS, seed);
  if (seed == 0) seed = analogRead(0);
  seed *= SEED_MULTIPLIER;
  EEPROM.put(EEPROM_ADDRESS, seed);
  randomSeed(seed);
}