如何打印与单词Arduino绑定的变量?

0 c++ arrays random arduino random-seed

我需要我的Arduino代码打印出被替换为变量的随机单词.因此,就像我将有一个随机数生成器一样,随机数字吐出一个单词,然后作为一个变量需要打印出来.这是我现在的代码,对不起,我还是Arduino的初学者.

long randnumber = 0;

int aye = 1;
int sup = 2;
int boi = 3;
int bruv = 4;

void setup() {
  Serial.begin(9600); // Starts the serial communication

}

void loop() {
int randnumber = 0;
  randnumber = random(0,4);
  Serial.println(randnumber);

}
Run Code Online (Sandbox Code Playgroud)

Joh*_*opp 5

您需要将单词放入数组中:

const char *words[] = {"aye", "sup", "boi", "bruv"};
Run Code Online (Sandbox Code Playgroud)

然后选择一个随机索引并在该索引处发送单词:

// Calculate the number of words. Better than hardcoding
// 4. If you add/remove words from array, this code
// won't have to change
int num_words = sizeof(words) / sizeof(words[0]);
randnumber = random(0, num_words);
Serial.println(words[randnumber]);
Run Code Online (Sandbox Code Playgroud)

您还应该为RNG播种,否则每次都会获得相同的结果.在PC上,人们经常使用当前时间播种RNG,但Arduino上没有时钟,因此更难.这里有一个很好的讨论:在Arduino中获得一个真正随机的数字.