在 Arduino 中生成隨機數
產生隨機數是微控制器的一項關鍵要求。隨機數有多種應用。我們不再贅述。你肯定有一個應用想法,才會來到本頁。在 Arduino 中生成隨機數非常容易,這要感謝內建 random() 函式。
語法
random(min, max)
或者
random(max)
其中 min 預設值為 0。
Min 為包含值,而 max 為不包含值。因此, random(10,50) 將返回 10 到 49(包含 10 和 49)之間的隨機整數。random(100) 將返回 0 到 99(包含 0 和 99)之間的隨機數。請注意,random 函式的返回型別為 long。
示例
void setup() { // put your setup code here, to run once: Serial.begin(9600); Serial.println(); long r1 = random(100); Serial.println(r1); } void loop() { // put your main code here, to run repeatedly: }
輸出
序列埠監視器輸出如下所示 −
忽略垃圾輸出。每次重置板時,都會列印一些垃圾。但你可以看到,每次列印的隨機數都不相同。
廣告