分享

Arduino如何产生随机数

 心灵地图sxh 2018-08-17

描述

randomSeed() 初始化随机数发生器,从而在任意点启动随机数的序列,这个序列虽然很长并且随机,但是过程是一致的。如果程序的后续运行对于random()产生的随机数序列差异性要求非常严格,那么请使用一个相对随机的输入来初始化randowmSeed()发生器,比如可以使用analogRead()来读取悬空的管脚。相反,有时候需要随机数序列重复,启动随机数序列之前可以使用一个固定的数来调用randomSeed()进行初始化。

参数

long int - 传递数据来产生随机数序列

返回

示例

long randNumber;

void setup(){
  Serial.begin(9600);
  randomSeed(analogRead(0));
}

void loop(){
  randNumber = random(300);
  Serial.println(randNumber);

  delay(50);
}




random()

描述

本函数生成随机数

语法

random(max)
random(min, max)

参数

min - 随机数最小值,随机数包括此值 (可选参数)

max - 随机数最大值,随机数不包括此值

返回

返回介于最小最大值之间的随机数(长整型), 最小值<=返回<最大值

提示

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.
 

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);
}

如需更详细资料,如有好资源分享,请加入QQ交流群:214461008

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多