【问题标题】:How to print a variable that is tied to a word Arduino?如何打印与 Arduino 相关的变量?
【发布时间】:2019-01-09 13:08:49
【问题描述】:

我需要我的 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);

}

【问题讨论】:

    标签: c++ arrays random arduino random-seed


    【解决方案1】:

    你需要把单词放入一个数组中:

    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

    【讨论】:

    • 您链接的问题是关于获得真正的随机性而不是伪随机性,而为 prng 选择种子并不会减少伪随机性。并不是说你写错了什么,只是如果你选择一个好的种子,它可能会被误解为能够从 prng 中获得真正的随机性
    • @user463035818 是的。我只是包含了链接,因为一些答案涉及挑选好种子。 randomSeed(analogRead(0)) 对于这个应用程序来说可能已经足够了。
    • @JohnnyMopp 嘿,非常感谢您的快速而精彩的回答。我在凌晨 1 点发布了这篇文章,当我醒来时,我的问题得到了解答,太棒了。现在将尝试在我的代码中实现它。 ;-)))
    猜你喜欢
    • 1970-01-01
    • 2013-12-17
    • 1970-01-01
    • 1970-01-01
    • 2018-08-04
    • 2018-09-05
    • 1970-01-01
    • 1970-01-01
    • 2019-02-01
    相关资源
    最近更新 更多