⭐⭐ Advanced beginner
⏱️ 15 minutes
Electronic dice
You make a dice made of light. Press the button: the lights roll for a moment, and then you see what you rolled. 1 to 6 lights!
🧰 What do you need?
🗺️ Wiring diagram
Follow the wires from the Arduino to each part. You can choose the wire colors yourself.
| From | To |
|---|---|
Arduino UNO · D2 |
Push button · 1 |
Push button · 2 |
Arduino UNO · GND |
Arduino UNO · D6 |
RGB LED ring (8 LEDs) · DI |
Arduino UNO · 5V |
RGB LED ring (8 LEDs) · 5V |
Arduino UNO · GND |
RGB LED ring (8 LEDs) · GND |
🛠️ This is how you build it
- Place the push button across the gap in the breadboard: one leg to pin 2, and a leg on the other side to GND.
- Connect the LED ring: DI to pin 6, 5V to 5V, and GND to GND.
💻 The code
// Electronic dice
// Press the button: the LED ring rolls for a moment and then lights up 1 to 6 LEDs.
#include <Adafruit_NeoPixel.h>
const int BUTTON_PIN = 2; // Push button on pin 2 (other side to GND)
const int RING_PIN = 6; // DI of the LED ring on pin 6
const int NUM_LEDS = 8;
Adafruit_NeoPixel ring(NUM_LEDS, RING_PIN, NEO_GRB + NEO_KHZ800);
// Light up a number of LEDs in one color
void showNumber(int number, uint32_t color) {
ring.clear();
for (int i = 0; i < number; i++) {
ring.setPixelColor(i, color);
}
ring.show();
}
void setup() {
pinMode(BUTTON_PIN, INPUT_PULLUP);
randomSeed(analogRead(A0)); // Makes the dice truly random
ring.begin();
ring.setBrightness(50);
ring.show();
}
void loop() {
if (digitalRead(BUTTON_PIN) == LOW) {
// A short "roll": quickly changing numbers, a bit slower each time
for (int i = 0; i < 15; i++) {
showNumber(random(1, 7), ring.Color(0, 80, 255));
delay(40 + i * 10);
}
int roll = random(1, 7); // A number from 1 to 6
showNumber(roll, ring.Color(0, 255, 60)); // The real number in green
delay(500);
}
}
🧠 What does the code do?
random(1, 7)chooses a random number from 1 to 6.- First we show fast-changing numbers in blue. This makes it look like the dice is rolling.
- Then
showNumber()shows the real number in green.
🎯 Try this…
- Give each number its own color
- Make a buzzer beep briefly when the dice stops
- Make it a dice from 1 to 8
🚀 Build this project with Codey: open codey.online/starter-kits/uno/projects/dice and click MAKE THIS. Then the code and the wiring diagram are ready right away.
Codey Online is a product of OTRONIC