Guides · 8 min read

Arduino Electronic Dice: 7 LEDs, Button and Shake-to-Roll

Build an Arduino electronic dice: 7-LED face, roll with a button or by shaking an SW-420, random and randomSeed, rolling animation, two MAX7219 dice, Pico.

An Arduino electronic dice is a small game project that arranges seven LEDs in the pip pattern of a real die and shows a random number from 1 to 6 when you press a button. The wiring is simple and the code is short, yet it hides real programming topics: arrays, bit patterns, generating random numbers with random() and randomSeed(), reading a button and making an animation. That makes it a great first project for Arduino beginners and for teachers looking for a board game to play in class.

In this article we'll first work out the LED layout and which LEDs each face lights up in a table, then build a button-rolled dice and, after that, a shake-to-roll version with an SW-420 vibration sensor. Next you'll see a clever 4-pin circuit, a two-dice version on MAX7219 LED matrices and MicroPython code for the Raspberry Pi Pico. Finally you'll learn how to test whether your dice is really fair.

LED for the Arduino dice project
Every pip is one LED: 7 LEDs, each with its own resistor, are all you need.

How does an electronic dice work?

The pips on a real die always land on one of the same seven positions: the four corners, the two middle positions on the left and right, and the exact centre. So seven LEDs are enough to show all six faces. When Arduino sees the button pressed, it shows quickly changing faces for a moment to give the feeling of a rolling die, then picks a random number from 1 to 6 and lights that number's pattern on the LEDs. The whole job is three steps: read the input, generate a random number, show the pattern.

PartQtyNote
Arduino Uno or Nano1A Pico or ESP32 works too
5 mm LED (single colour)7Same colour and brand gives even brightness
220–330 Ω resistor7One resistor per LED
Push button1Uses the internal pull-up, no resistor needed
SW-420 vibration sensor1 (optional)For shake-to-roll
MAX7219 8x8 LED matrix2 (optional)For the two-dice version
Breadboard and jumper wires1 setPerfboard for a permanent build

A dice face with 7 LEDs: layout and mapping table

Let's give the LEDs letters: a, b, c top to bottom in the left column, d in the centre, and e, f, g top to bottom in the right column. The middle of the top and bottom rows is never used on any face, so there's no LED there. In the code we'll store each face as a 7-bit number: the rightmost bit is a, the leftmost is g. If a bit is 1, that LED lights. That way "show 5" simply means writing the bits of one byte to the pins in turn.

PositionLeft columnMiddle columnRight column
Top rowaemptye
Middle rowbdf
Bottom rowcemptyg
FaceLEDs onPattern in the code (g…a)
1d0b0001000
2a, g0b1000001
3a, d, g0b1001001
4a, c, e, g0b1010101
5a, c, d, e, g0b1011101
6a, b, c, e, f, g0b1110111

Arduino dice wiring

ConnectionArduino UnoESP32Raspberry Pi Pico
LED a / b / c (left column)D4 / D5 / D6GPIO 16 / 17 / 18GP2 / GP3 / GP4
LED d (centre)D7GPIO 19GP5
LED e / f / g (right column)D8 / D9 / D10GPIO 21 / 22 / 23GP6 / GP7 / GP8
LED cathodes (through a resistor)GNDGNDGND
Button (other leg to GND)D3GPIO 4GP15
SW-420 DOD2 (interrupt INT0)GPIO 27GP14
SW-420 VCC5V3V33V3(OUT)
Give every LED its own resistor; if you put one resistor in the shared cathode of all seven, brightness drops as more LEDs light, and face 6 looks clearly dimmer than face 1. At 5 V, 220 Ω means about 13 mA for a red LED; work out the value for your own LED with the LED resistor calculator. On the ESP32 and Pico, power the SW-420 module from 3.3 V, otherwise its DO output gives 5 V.

random() and randomSeed(): is the dice really random?

Arduino's random() doesn't produce true randomness; it calculates a sequence of "random-looking" numbers with a mathematical formula. As long as the starting point (the seed) stays the same, the sequence is the same at every power-up: without a seed your dice rolls 5, 2, 6... in the same order every time it starts. randomSeed() changes that starting point. The classic trick is to read the noise of a floating analog pin: randomSeed(analogRead(A0)). That value often stays within a narrow range, though. For a dice there's a much better source: the moment the button is pressed. No finger can hit the same instant to the microsecond, so calling randomSeed(micros()) at the press makes every roll unpredictable. And watch out for a common mistake: random(1, 7) returns 1 to 6, because the upper limit is excluded.

Step by step: an Arduino dice rolled with a button

  1. Place the seven LEDs on the breadboard like a 3×3 grid; leave the middle of the top and bottom rows empty.
  2. Connect each LED's long leg (anode) to the pin in the table and its short leg (cathode) through a resistor to the GND rail.
  3. Connect one leg of the button to D3 and the diagonally opposite leg to GND. If you're not sure which button legs are linked, see the connecting a button to Arduino article.
  4. Upload the code below; face 6 should light at power-up. An LED that stays dark is in backwards.
  5. Press the button: the faces change more and more slowly, then the result blinks twice and is printed on the Serial Monitor.
C++ (Arduino IDE)
1// Arduino elektronik zar: 7 LED + buton / Arduino electronic dice: 7 LEDs + button
2//  a . e
3//  b d f      a-b-c sol sütun, d orta, e-f-g sağ sütun / a-b-c left column, d centre, e-f-g right column
4//  c . g
5const int LED_PINS[7] = { 4, 5, 6, 7, 8, 9, 10 };   // a, b, c, d, e, f, g
6const int BUTTON = 3;                               // GND'ye basan buton / button to GND
7
8// Her yüz için 7 bitlik desen: bit0 = a ... bit6 = g / 7-bit pattern per face: bit0 = a ... bit6 = g
9const byte FACES[7] = {
10  0b0000000,   // 0: hepsi sönük / all off
11  0b0001000,   // 1: d
12  0b1000001,   // 2: a, g
13  0b1001001,   // 3: a, d, g
14  0b1010101,   // 4: a, c, e, g
15  0b1011101,   // 5: a, c, d, e, g
16  0b1110111    // 6: a, b, c, e, f, g
17};
18
19void showFace(int face) {
20  for (int i = 0; i < 7; i++) digitalWrite(LED_PINS[i], bitRead(FACES[face], i));
21}
22
23int rollDice() {
24  // Yuvarlanma: giderek yavaşlayan rastgele yüzler / rolling: random faces that slow down
25  for (int wait = 30; wait < 260; wait = wait * 115 / 100) {
26    showFace(random(1, 7));          // 1-6 (7 dahil değil) / 1-6 (7 is excluded)
27    delay(wait);
28  }
29  int result = random(1, 7);
30  for (int i = 0; i < 2; i++) {      // sonucu iki kez yakıp söndür / blink the result twice
31    showFace(0);      delay(120);
32    showFace(result); delay(180);
33  }
34  return result;
35}
36
37void setup() {
38  for (int i = 0; i < 7; i++) pinMode(LED_PINS[i], OUTPUT);
39  pinMode(BUTTON, INPUT_PULLUP);
40  Serial.begin(9600);
41  randomSeed(analogRead(A0));        // boştaki A0'ın gürültüsü / noise of the floating A0 pin
42  showFace(6);
43}
44
45void loop() {
46  if (digitalRead(BUTTON) == LOW) {
47    randomSeed(micros());            // basma anı tohum olur / the press moment becomes the seed
48    int result = rollDice();
49    Serial.print(F("Zar / Dice: "));
50    Serial.println(result);
51    while (digitalRead(BUTTON) == LOW) {}   // bırakılmasını bekle / wait for release
52    delay(50);
53  }
54}
Code partJob
LED_PINS[7]Pins of LEDs a to g; change the order and the patterns shift too
FACES[7]7-bit pattern of each face; element 0 is all off
bitRead(FACES[face], i)Reads bit i of the pattern and turns the LED on or off
wait = wait * 115 / 100Each frame waits 15% longer, so the dice seems to slow down and stop
randomSeed(micros())Uses the moment of the press as the seed, so the order isn't the same after every start
while (digitalRead(BUTTON) == LOW)No new roll until the button is released

Shake to roll: the SW-420 vibration sensor

SW-420 vibration sensor module
SW-420: the spring switch inside opens and closes when shaken, and the module turns that into digital pulses.

If you want the dice to roll when you shake its box, the SW-420 module does the job. During vibration the sensor doesn't produce one long signal but a burst of short pulses; checking it with digitalRead() in loop() misses most of them. So the code below connects DO to the interrupt on D2 and counts every level change. Every 200 milliseconds it looks at the counter; if the number of changes passes SHAKE_LIMIT, the dice counts as shaken. Because we count level changes (CHANGE), it doesn't matter if the module's output logic is inverted. Ways to catch the pulses and adjust sensitivity are covered in detail in the SW-420 vibration sensor article.

C++ (Arduino IDE)
1// Sallayınca atılan zar: SW-420 + buton + 7 LED / Shake-to-roll dice: SW-420 + button + 7 LEDs
2const int LED_PINS[7] = { 4, 5, 6, 7, 8, 9, 10 };   // a, b, c, d, e, f, g
3const int SHAKE_PIN = 2;                            // SW-420 DO (kesme INT0) / SW-420 DO (interrupt INT0)
4const int BUTTON = 3;
5const byte FACES[7] = { 0b0000000, 0b0001000, 0b1000001, 0b1001001, 0b1010101, 0b1011101, 0b1110111 };
6
7const unsigned int SHAKE_LIMIT = 6;      // 200 ms içinde bu kadar değişim = sallandı / this many edges in 200 ms = shaken
8volatile unsigned int shakeEdges = 0;
9
10void onShake() { shakeEdges++; }         // her seviye değişiminde sayılır / counts every level change
11
12void showFace(int face) {
13  for (int i = 0; i < 7; i++) digitalWrite(LED_PINS[i], bitRead(FACES[face], i));
14}
15
16int rollDice() {
17  for (int wait = 30; wait < 260; wait = wait * 115 / 100) {
18    showFace(random(1, 7));
19    delay(wait);
20  }
21  int result = random(1, 7);
22  showFace(result);
23  return result;
24}
25
26void setup() {
27  for (int i = 0; i < 7; i++) pinMode(LED_PINS[i], OUTPUT);
28  pinMode(BUTTON, INPUT_PULLUP);
29  pinMode(SHAKE_PIN, INPUT);
30  attachInterrupt(digitalPinToInterrupt(SHAKE_PIN), onShake, CHANGE);
31  Serial.begin(9600);
32  randomSeed(analogRead(A0));
33  showFace(6);
34}
35
36void loop() {
37  static unsigned long windowStart = 0;
38  bool roll = false;
39
40  if (millis() - windowStart >= 200) {   // 200 ms'lik pencereler / 200 ms windows
41    noInterrupts();
42    unsigned int edges = shakeEdges;
43    shakeEdges = 0;
44    interrupts();
45    windowStart = millis();
46    if (edges >= SHAKE_LIMIT) roll = true;
47  }
48  if (digitalRead(BUTTON) == LOW) roll = true;
49
50  if (roll) {
51    randomSeed(micros());
52    int result = rollDice();
53    Serial.print(F("Zar / Dice: "));
54    Serial.println(result);
55    delay(800);                          // zar dururken gelen titreşimleri yok say / ignore vibration while it settles
56    noInterrupts();
57    shakeEdges = 0;
58    interrupts();
59    while (digitalRead(BUTTON) == LOW) {}
60  }
61}

A dice with only 4 pins: LED groups

Look carefully at the patterns in the table and you'll see the LEDs always light in pairs: a with g, c with e, and b with f always turn on together, while d stands alone. Thanks to this, four pins are enough instead of seven. Wire the two LEDs of each pair in parallel to the same pin, each with its own resistor; with 220 Ω that's about 13 mA per LED and about 26 mA per pin. That's below the Uno's 40 mA absolute maximum per pin but above the 20 mA recommended for continuous use; with 330 Ω resistors you drop to about 18 mA per pin. You can use the three pins you've saved for a second dice, a buzzer or a score display.

Group (pin)LEDsFaces it lights
Group 1d (centre)1, 3, 5
Group 2a + g (one diagonal)2, 3, 4, 5, 6
Group 3c + e (other diagonal)4, 5, 6
Group 4b + f (middle row)Only 6

Two dice on MAX7219 LED matrices

For two-dice games such as backgammon or Monopoly, chain two 8x8 MAX7219 matrices: the first module's DOUT goes to the second one's DIN. On the Uno, connect DIN to D11, CLK to D13, CS to D10 and VCC to 5V; the button stays on D3. Each pip is drawn as a 2×2 pixel square, with pips starting at pixels 0, 3 and 6, leaving a one-pixel gap between them for a look very close to a real die. Since we use the same FACES patterns, the code's logic is exactly the same as the LED version. Installing the MD_MAX72XX library and the module types are explained in the MAX7219 LED matrix article.

C++ (Arduino IDE)
1// İki zar, iki MAX7219 8x8 matris (MD_MAX72XX) / Two dice on two MAX7219 8x8 matrices (MD_MAX72XX)
2#include <MD_MAX72xx.h>
3#include <SPI.h>
4
5#define HARDWARE_TYPE MD_MAX72XX::FC16_HW   // görüntü bozuksa GENERIC_HW dene / try GENERIC_HW if the image is scrambled
6#define MAX_DEVICES 2                       // zincirde 2 matris / 2 matrices in the chain
7#define CS_PIN 10                           // DIN = D11, CLK = D13
8const int BUTTON = 3;
9
10MD_MAX72XX mx = MD_MAX72XX(HARDWARE_TYPE, CS_PIN, MAX_DEVICES);
11
12const byte FACES[7] = { 0b0000000, 0b0001000, 0b1000001, 0b1001001, 0b1010101, 0b1011101, 0b1110111 };
13const byte PIP_ROW[7] = { 0, 1, 2, 1, 0, 1, 2 };   // a..g noktalarının satırı (0-2) / row of pips a..g (0-2)
14const byte PIP_COL[7] = { 0, 0, 0, 1, 2, 2, 2 };   // a..g noktalarının sütunu (0-2) / column of pips a..g (0-2)
15const byte POS[3] = { 0, 3, 6 };                   // 2x2 noktanın piksel başlangıcı / pixel start of each 2x2 pip
16
17void drawDie(uint8_t device, int face) {
18  for (uint8_t r = 0; r < 8; r++)
19    for (uint8_t c = 0; c < 8; c++) mx.setPoint(r, device * 8 + c, false);   // zarı temizle / clear the die
20  for (uint8_t i = 0; i < 7; i++) {
21    if (!bitRead(FACES[face], i)) continue;
22    uint8_t r = POS[PIP_ROW[i]], c = device * 8 + POS[PIP_COL[i]];
23    mx.setPoint(r, c, true);     mx.setPoint(r, c + 1, true);       // 2x2 nokta / 2x2 pip
24    mx.setPoint(r + 1, c, true); mx.setPoint(r + 1, c + 1, true);
25  }
26}
27
28void showDice(int d1, int d2) {
29  mx.control(MD_MAX72XX::UPDATE, MD_MAX72XX::OFF);   // çizerken güncelleme kapalı / no updates while drawing
30  drawDie(0, d1);
31  drawDie(1, d2);
32  mx.control(MD_MAX72XX::UPDATE, MD_MAX72XX::ON);    // tek seferde göster / show at once
33}
34
35void setup() {
36  mx.begin();
37  mx.control(MD_MAX72XX::INTENSITY, 3);              // parlaklık 0-15 / brightness 0-15
38  pinMode(BUTTON, INPUT_PULLUP);
39  Serial.begin(9600);
40  randomSeed(analogRead(A0));
41  showDice(6, 6);
42}
43
44void loop() {
45  if (digitalRead(BUTTON) != LOW) return;
46  randomSeed(micros());
47  for (int wait = 30; wait < 260; wait = wait * 115 / 100) {
48    showDice(random(1, 7), random(1, 7));
49    delay(wait);
50  }
51  int d1 = random(1, 7), d2 = random(1, 7);
52  showDice(d1, d2);
53  Serial.print(d1); Serial.print(F(" + ")); Serial.print(d2);
54  Serial.print(F(" = ")); Serial.println(d1 + d2);
55  while (digitalRead(BUTTON) == LOW) {}
56  delay(50);
57}

Electronic dice with Raspberry Pi Pico (MicroPython)

To build the same circuit on a Pico, connect the LEDs to GP2–GP8 and the button between GP15 and GND. MicroPython uses random.randint(1, 6), and unlike Arduino the upper limit is included; keep that difference in mind when you switch between the two languages. On the Pico's 3.3 V pins the LED current is a little lower, but with 220–330 Ω the LEDs are still clearly visible; there's no need to strain the pins with smaller resistors. If MicroPython is new to you, start with the MicroPython basics article.

MicroPython
1# Raspberry Pi Pico elektronik zar (MicroPython) / Raspberry Pi Pico electronic dice (MicroPython)
2from machine import Pin
3import random, time
4
5leds = [Pin(n, Pin.OUT) for n in (2, 3, 4, 5, 6, 7, 8)]   # a, b, c, d, e, f, g -> GP2..GP8
6button = Pin(15, Pin.IN, Pin.PULL_UP)                    # GP15, basınca 0 / 0 when pressed
7FACES = (0b0000000, 0b0001000, 0b1000001, 0b1001001, 0b1010101, 0b1011101, 0b1110111)
8
9def show(face):
10    for i, led in enumerate(leds):
11        led.value((FACES[face] >> i) & 1)
12
13def roll():
14    wait = 30
15    while wait < 260:                     # giderek yavaşlayan yuvarlanma / slowing roll
16        show(random.randint(1, 6))        # randint'te 6 dahildir / randint includes 6
17        time.sleep_ms(wait)
18        wait = wait * 115 // 100
19    result = random.randint(1, 6)
20    show(result)
21    return result
22
23show(6)
24while True:
25    if button.value() == 0:
26        random.seed(time.ticks_us())      # basma anı tohum / press moment as the seed
27        print("Zar / Dice:", roll())
28        while button.value() == 0:        # bırakılmasını bekle / wait for release
29            time.sleep_ms(10)
30        time.sleep_ms(50)
31    time.sleep_ms(10)

Is your dice fair? A simple statistics test

A fair dice means each face comes up with the same probability, 1/6. To see this, call random(1, 7) 6000 times in setup(), add up each result in a counter array and print the totals on the Serial Monitor. The expected value for each face is 1000, but it won't be exactly 1000: with this many rolls the standard deviation is about 29, so counts mostly landing between 940 and 1060 is normal. If one face is always above 1100 or below 900, there's a bug in your code; the most common one is writing random(1, 6) and never producing a 6. The mathematical bias in Arduino's random(1, 7) is small enough to ignore.

Ideas to take the dice project further

  • Idea: Play a short "click click" sound with a passive buzzer on every roll; see the what is a buzzer article for how.
  • Idea: Also show the result on a 7-segment display and keep count of the total rolls.
  • Idea: Make a two-player "highest roll wins" game, with a button and LED for each player.
  • Idea: If you enjoy randomness, move on to the roulette and memory games in the Arduino game projects list.
  • Idea: Make the dice portable with a battery and sleep mode: shaking wakes it to roll, and it goes back to sleep after 30 seconds.
  • Idea: Use RGB LEDs and show each player's dice in a different colour.

Common problems and fixes

SymptomLikely causeFix
The dice never rolls a 6random(1, 6) was used, the upper limit is excludedUse random(1, 7)
The same sequence appears at every power-upNo randomSeed()Call randomSeed(micros()) at the press
One LED never lightsLED in backwards or wrong pinLong leg to the pin, short leg via the resistor to GND
Faces look scrambled (e.g. a line instead of 2)LED_PINS order doesn't match the physical layoutCompare the a–g order with the table
One press rolls twiceButton bounceWait for release and add a 50 ms delay
Shaking doesn't roll, or it rolls by itselfSW-420 sensitivity or SHAKE_LIMIT is offAdjust the potentiometer, raise or lower SHAKE_LIMIT
The MAX7219 image is rotated or garbledDifferent module typeSet HARDWARE_TYPE to GENERIC_HW or PAROLA_HW
When you make the dice permanent, space the LEDs evenly on perfboard like a real die face and put frosted acrylic or paper over them; the pips look softer and easier to read. If you're designing the box yourself, light face 6 once, take a photo and check on screen that the pips are evenly spaced.

An electronic dice may look like a small project, but it teaches many basics at once: arrays, bit operations, random numbers, interrupts and animation. You can follow the circuit diagram and code of the "Dice Project" step by step in the BlueGrays app, then build on the same ideas in game projects such as "Arduino Memory Game (4 LEDs + 4 Buttons + Buzzer)".

Frequently asked questions

How do you make an electronic dice with Arduino?

Arrange seven LEDs in the pip pattern of a real die, connect each to an Arduino pin through a resistor and add a button. In the code, when the button is pressed, generate a number from 1 to 6 with random(1, 7) and light that number's pattern on the LEDs. A short rolling animation makes it look more realistic.

Why does Arduino random give the same numbers every time?

random() doesn't produce true randomness but a pseudo-random sequence calculated from a starting value. If that value doesn't change, the sequence is the same at every power-up. Call randomSeed(analogRead(A0)) in setup(), or randomSeed(micros()) when the button is pressed, and you'll get different results each time.

Why doesn't random(1, 6) ever return 6?

In Arduino's random(min, max), the lower limit is included and the upper limit is excluded. So random(1, 6) only produces numbers from 1 to 5. For a dice write random(1, 7); MicroPython's random.randint(1, 6), on the other hand, includes both limits.

How many LEDs does an electronic dice need?

Seven LEDs are enough to show all six faces: four corners, two side middles and the centre. Because the LEDs always light in pairs, you can also drive them with 4 pins. For two dice use 14 LEDs or two MAX7219 8x8 matrices.

How do you make a shake-to-roll dice?

Add an SW-420 vibration sensor to the dice box and connect its DO output to an interrupt pin. Count level changes in the interrupt routine; if there are more than a set number within a short time window, roll the dice. For a more precise result you can use an MPU6050 accelerometer instead.

What resistor should I use for an Arduino dice?

On a 5 V Arduino, 220–330 Ω suits standard 5 mm LEDs; with 220 Ω about 13 mA flows through a red LED. Giving every LED its own resistor keeps the brightness even no matter how many LEDs are lit. On the 3.3 V Pico and ESP32 the current is a little lower, but LEDs are still clearly visible with 220 Ω.

See all projects
LED Blink
AR-1Beginner

LED Blink

The very first hello of electronics: switching a single LED on and off. The Arduino keeps the LED on for one second and off for one second, so you can easily follow every blink.

4.6(203)
1382
LED Control with a Push Button (Push)
AR-9Beginner

LED Control with a Push Button (Push)

Just like a doorbell: the light stays on as long as you press, and goes off when you let go.

4.8(118)
283
Toggle an LED with a Button (On/Off)
AR-10Beginner

Toggle an LED with a Button (On/Off)

Press the button once and the light comes on, press it again and it goes off, just like the light switch in your room.

4.7(105)
183
Dice Project
AR-79Intermediate
Premium

Dice Project

No more lost dice during board games: every time you press the button, a random number from 1 to 6 appears on the 7-segment display.

5.0(48)
68
Arduino Memory Game (4 LEDs + 4 Buttons + Buzzer)
AR-93Advanced
Premium

Arduino Memory Game (4 LEDs + 4 Buttons + Buzzer)

Do you trust your memory? Four colored LEDs light up in a sequence, each playing its own note, and you repeat the same order by pressing the buttons.

4.8(46)
69
Arduino Reaction Time Test with Sound Cue: Measure Your Reflexes in Milliseconds (LCD + Buzzer + 3 LEDs)
AR-95Intermediate
Premium

Arduino Reaction Time Test with Sound Cue: Measure Your Reflexes in Milliseconds (LCD + Buzzer + 3 LEDs)

How fast are your reflexes? Press the button: the red LED says get ready, the yellow LED says steady and a random wait of 1.5 to 3.5 seconds begins. The moment the green LED lights up and the buzzer beeps, press again; your reaction time appears on the I2C LCD in milliseconds, with your session best and average below it. Press before green and the screen shows TOO EARLY! with a losing sound. Hold the button for a new player, so everyone races the same wait order.

4.6(34)
51
Raspberry Pi Pico Button Controlled LED (Push)
PI-9Beginner
Premium

Raspberry Pi Pico Button Controlled LED (Push)

First input project with Pico — button read! LED lights while button is pressed, off when released. This is the big step after LED animations: signal input from the world to Pico. Learn Pin.IN (input mode), Pin.PULL_UP (internal pull-up resistor — standard for buttons), button.value() reading. GP14 LED, GP2 button (internal PULL_UP). Pressed = LOW (0), released = HIGH (1) — reverse logic seems confusing at first but is industry standard.

11