Random()
来自YFRobotwiki
描述
随机函数产生伪随机数。
语法
random(max) random(min, max)
参数
- min - 随机值的下限,包括(可选)
- max - 随机值的上限,不包含
返回
- min和max-1之间的随机数(long)
注意
如需要在一个random()序列上生成真正意义的随机数,在执行其子序列时使用randomSeed()函数预设一个绝对的随机输入,例如在一个断开引脚上的analogRead()函数的返回值。
反之,有些时候伪随机数的精确重复也是有用的。这可以在一个随机系列开始前,通过调用一个使用固定数值的randomSeed()函数来完成。
示例
long randNumber;
void setup(){
Serial.begin(9600);
// if analog input pin 0 is unconnected, random analog 如果模拟输入引脚0为断开,随机的模拟噪声
// noise will cause the call to randomSeed() to generate 将会调用randomSeed()函数在每次代码运行时生成
// different seed numbers each time the sketch runs. 不同的种子数值。
// randomSeed() will then shuffle the random function. randomSeed()将随机打乱random函数。
randomSeed(analogRead(0));
}
void loop() {
// print a random number from 0 to 299 打印一个0到299之间的随机数
randNumber = random(300);
Serial.println(randNumber);
// print a random number from 10 to 19 打印一个10到19之间的随机数
randNumber = random(10, 20);
Serial.println(randNumber);
delay(50);
}
扩展阅读
更多建议和问题欢迎反馈至 YFRobot论坛