Generating random numbers in Arduino is useful for games, patterns, or any project needing unpredictability. The core function is random(), but it produces the same sequence each reset unless you seed it with randomSeed(). This guide shows you how to use both correctly, avoid common pitfalls, and get truly varied results.
What You’ll Need
- An Arduino board (Uno, Nano, Mega, etc.)
- USB cable to connect to your computer
- Arduino IDE (version 1.8+ or 2.x) installed
- Optional: a breadboard, LED, and resistor if you want to test visually
Step-by-Step
- Open the Arduino IDE on your computer. Create a new sketch by clicking File > New.
- Understand the basic random() function. The syntax is
random(max)which returns a number from 0 to max-1, orrandom(min, max)which returns from min to max-1. For example,random(10)gives 0-9;random(5, 15)gives 5-14. - Write a simple sketch that prints random numbers to the Serial Monitor. Type this:
void setup() { Serial.begin(9600); } void loop() { int r = random(100); Serial.println(r); delay(1000); }Upload it and open the Serial Monitor (Tools > Serial Monitor). You’ll see numbers, but they repeat the same sequence every time you reset the board.
- Seed the random number generator to get different sequences. Add
randomSeed()insetup(). A common seed is an analog read from an unconnected pin:void setup() { Serial.begin(9600); randomSeed(analogRead(A0)); }Upload again. Now the sequence changes each reset. Note: pin A0 must be left floating (no wire connected) for best noise.
- Generate numbers in a range. Use two arguments. For a dice roll (1-6):
int dice = random(1, 7); // returns 1,2,3,4,5,6For a random delay between 500 and 2000 ms:
delay(random(500, 2001));Remember the upper bound is exclusive, so add 1 to include it.
- Use random() in a practical project. For example, blink an LED with random on/off times. Connect an LED to pin 13 with a resistor. Sketch:
void setup() { pinMode(13, OUTPUT); randomSeed(analogRead(A0)); } void loop() { digitalWrite(13, HIGH); delay(random(100, 2000)); digitalWrite(13, LOW); delay(random(100, 2000)); }Upload and watch the LED blink unpredictably.
- Consider using the newer
random()with a seed frommicros()for faster variation. If you callrandomSeed(micros())just before generating, you get different results even without a floating pin, but it’s less random over time. PreferanalogRead()for true entropy.
Common Mistakes
- Forgetting to seed: Without
randomSeed(), you get the same sequence every power-up. This is the #1 mistake. - Using a fixed seed:
randomSeed(12345)gives the same sequence every time. Only use a variable seed likeanalogRead(). - Off-by-one errors:
random(1,6)returns 1-5, not 1-6. Always remember the upper bound is exclusive. - Reading a pin that’s connected to something: If A0 is connected to a sensor or wire,
analogRead(A0)gives a predictable value, reducing randomness. - Calling
randomSeed()inside the loop: This resets the sequence each iteration, causing the same numbers to repeat if the seed is the same.
Tips
- Use a floating analog pin for seeding: Leave A0 unconnected for maximum noise. The value fluctuates due to electrical interference.
- Combine seeds: For better randomness, use
randomSeed(analogRead(A0) + analogRead(A1) + micros()). - Scale numbers without modulo bias: If you need a range that isn’t a power of two, using
%can bias results. For example,random(0, 100) % 10is fine, but for critical applications, userandom(min, max)directly. - For cryptographic randomness: Arduino’s
random()is not secure. For passwords or encryption, use an external module like a True Random Number Generator (TRNG) or a library likeEntropyfor better entropy. - Test your range: Use
Serial.print()to verify the output matches your expectations before relying on it in a project.
Troubleshooting
- Same numbers every time: You likely forgot to seed or used a constant seed. Add
randomSeed(analogRead(A0))insetup()and ensure A0 is unconnected. - Numbers are always 0: Check your range. If you write
random(0, 1), it only returns 0. Userandom(1, 2)for 1. - Numbers repeat in a short cycle: The built-in PRNG has a limited period. If you need long sequences, consider using a library like
RandomorPCGfor better quality. - Serial Monitor shows garbage: Make sure baud rate matches (9600 in the sketch and Serial Monitor). Also check that you’re printing correctly.
- Analog read always returns 1023: If A0 is connected to 5V, it reads max. Disconnect it or use a different unconnected pin.
- Program crashes or hangs: If you call
random()with a negative min or max, it may cause issues. Always use positive integers.
Frequently Asked Questions
Q: Why do I get the same numbers every time I reset my Arduino?
A: Because the random number generator starts with the same seed each time. Use randomSeed(analogRead(A0)) to change the seed based on noise.
Q: Can I generate a random float or decimal number?
A: Yes, but random() only returns integers. To get a float, divide: float r = random(0, 100) / 100.0; gives 0.00 to 0.99.
Q: How do I get a random number between 0 and 1?
A: Use random(0, 2) for 0 or 1, or random(0, 1000) / 1000.0 for a decimal.
Q: Is the Arduino random function truly random?
A: No, it’s pseudo-random. It’s fine for most hobby projects, but not for security. For better randomness, use an external source or the Entropy library.
Q: Can I use random() with negative numbers?
A: Yes, but be careful. random(-10, 10) returns -10 to 9. The upper bound is exclusive, so to include 10, use random(-10, 11).
Q: What is the maximum value random() can return?
A: The maximum is 2,147,483,647 (the largest signed 32-bit integer). But you’ll rarely need that many.
Related
- Random Number Generators: Why They’re Not Truly Random
- How to Split View in Google Sheets (Rows & Columns)
- How to Generate Random Numbers in JMP
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- How to Double Space in Microsoft Word for APA FormatTo double-space an APA paper in Microsoft Word, select the document text, then choose Home > Line and…
- Can You Insert a Digital Signature in Word?Yes. In Word for Microsoft 365 on Windows, you can add a signature line and sign it with…
- How to Freeze Top Row and First Column in ExcelFreeze the top row and first column together in Excel with Freeze Panes, plus fixes for common issues…
- Google Sheets Date Difference: Formulas and ExamplesIn Google Sheets, subtract the earlier date from the later date to get the difference in days: if…
- Add a Checkbox to the Excel Toolbar in Microsoft 365To add a checkbox to a worksheet in Microsoft 365, select the target cell or range and choose…
- Barefoot Investor Budget Spreadsheet: Build Your OwnA Barefoot Investor budget spreadsheet is a way to track the book’s money buckets, but the method does…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.