Skip to content

Ard Random Range

DodaTech 1 min read

In this tutorial, you'll learn about Arduino random() Returns Value Outside Expected Range. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

The Problem

random() returns unexpected values, including the maximum value.

Quick Fix

Wrong

int r = random(100);  // Returns 0-99 (not 0-100)
r is never 100, which may be unexpected.
// random(max) returns 0 to max-1
int r1 = random(100);  // 0-99

// random(min, max) returns min to max-1
int r2 = random(10, 100);  // 10-99

// For inclusive range 0-100:
int r3 = random(0, 101);  // 0-100

Serial.print(r1); Serial.print(' ");
Serial.print(r2); Serial.print(" ');
Serial.println(r3);
42 57 100  (example values within expected ranges).

Prevention

random(max) returns 0 to max-1. random(min, max) returns min to max-1. For inclusive range [0, max], use random(0, max+1). For inclusive [min, max], use random(min, max+1). The upper bound is exclusive.

DodaTech engineers apply these same patterns across Doda Browser, DodaZIP, and Durga Antivirus Pro for production IoT reliability.

FAQ

### How do I get a random float?

Use (float)random(0, 10001) / 10000.0 for 4-decimal precision, or random(0, 1001) / 1000.0 for 3 decimals.

Can I get a random boolean?

Yes: bool b = random(2); returns true or false with equal probability.

What is the maximum value for random()?

The maximum is 2147483647 (2^31 - 1). For larger ranges, combine two random() calls.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro