Arduino 每次草图 运行 从数组中选择一个 运行dom 词

Arduino Pick a random word from array every time sketch is ran

我有一些代码:

char *fruits[]={"Lettuce", "Tomato", "Pineapple", "Apple"}; //This is the array
long fruit1; 
void setup(){
 Serial.begin(9600);
 randomSeed(500);
 fruit1 = random(sizeof(fruits)/sizeof(char*));
 Serial.println(fruits[fruit1]);//Prints random in serial
}

此代码在 arduino sketch 第一次 运行 时选择 运行dom fruit,但每隔一次我 运行 它使用相同的 运行 dom fruit it 第一次采摘草图是运行。我希望它在每次草图为 运行 时从数组中挑选一个 运行dom 水果,这意味着每次我打开和关闭它时我都想看到一个不同的 运行dom 水果来自最后。对不起,如果我做错了什么。

代码来源:https://forum.arduino.cc/index.php?topic=45653.0

对于给定的种子值,您将始终获得相同的随机数序列。每次调用设置时都需要不同的种子:

randomSeed()

randomSeed() initializes the pseudo-random number generator, causing it to start at an arbitrary point in its random sequence. This sequence, while very long, and random, is always the same.

If it is important for a sequence of values generated by random() to differ, on subsequent executions of a sketch, use randomSeed() to initialize the random number generator with a fairly random input, such as analogRead() on an unconnected pin.

Conversely, it can occasionally be useful to use pseudo-random sequences that repeat exactly. This can be accomplished by calling randomSeed() with a fixed number, before starting the random sequence.

我不完全了解 PRNG 函数在较低级别的工作方式,但我相信保持 seed 相同可能是导致问题的原因。

arduino reference 建议您按照以下方式实现随机数生成代码,从而帮助您解决此问题 -

long randNumber;

void setup() {
  Serial.begin(9600);

  // if analog input pin 0 is unconnected, random analog
  // noise will cause the call to randomSeed() to generate
  // different seed numbers each time the sketch runs.
  // randomSeed() will then shuffle the random function.
  randomSeed(analogRead(0));
}

void loop() {
  // print a random number from 0 to 299
  randNumber = random(300);
  Serial.println(randNumber);

  // print a random number from 10 to 19
  randNumber = random(10, 20);
  Serial.println(randNumber);

  delay(50);
}