Go Down

Topic: randomseed on attiny (Read 969 times) previous topic - next topic

penguin

I would like to use randomseed to generate different random numbers each time I run my program.  I am using an attiny and do not have any unused pins, so I can't use randomseed(analogRead(0)) as recommended on the randomseed reference page.  Is there another way to ensure that I get a different random number each time?

Thanks!

WizenedEE

You could save a value to EEPROM and then increment it each time you run the code.

penguin

I think I understand what you mean, but ideally, I'd like it to increment / decrement the value stored in EEPROM by a different random amount each time.  Do you have ideas of how to do this?  Thanks for your help!

WizenedEE

If you give the randomseed function a different value every time, it should come up with a completely different start point for the random values, so just incrementing it by 1 will work.

penguin

I'm getting repeating values every fourth time I run the following code:

Code: [Select]

void setup(){
  Serial.begin(9600);
  int id = EEPROM.read(0);
  randomSeed(id);
  id = random(50,125);
  EEPROM.write(0, id+1);
  Serial.println(id);
}

void loop(){
}


Is this what you meant?

WizenedEE

Code: [Select]

void setup(){
  Serial.begin(9600);
  unsigned int id = EEPROM.read(0);
  randomSeed(id);
//  id = random(50,125);
  EEPROM.write(0, id+1);
  Serial.println(id);
  Serial.println(random(100));
}

void loop(){
}


I'm no expert in EEPROM, but you may want to

Coding Badly


http://arduino.cc/forum/index.php/topic,66206.msg537783.html#msg537783

penguin

thanks for your code, WizenedEE.  I found that the "random" number generated by your code always ended up being 7 greater than the last one up to 100.  I edited your code to increment the EEPROM value by a random number, and it seems to work ok:

Code: [Select]

void setup(){
  Serial.begin(9600);
  unsigned int id = EEPROM.read(0);
  randomSeed(id);
//  id = random(50,125);
  EEPROM.write(0, id+random(10));
  id = random(50,125);
  Serial.println(id);
}

void loop(){
}

Go Up