我需要我的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);
}
答案 0 :(得分:5)
您需要将单词放入数组:
const char *words[] = {"aye", "sup", "boi", "bruv"};
然后选择一个随机索引并在该索引处发送单词:
// 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]);
您还应该为RNG设置种子,否则每次将获得相同的结果。在PC上,人们通常使用当前时间来播种RNG,但是Arduino上没有时钟,因此更加困难。这方面的讨论很好:Getting a truly random number in Arduino。