Arduino Dice Roll Simulator using a 7-segment display and button to generate random numbers from 1 to 6 with hardware and software setup.
// Dice roll simulator (1-6) with Arduino and 7-segment display
// Pin definition for 7-segment display segments (common cathode)
const int segmenti[7] = {2, 3, 4, 5, 6, 7, 8}; // A,B,C,D,E,F,G
// Button pin
const int pinPulsante = 9;
// Segment map for numbers 1 to 6
// Each array indicates which segments to light (1=on, 0=off)
// Segment order: A,B,C,D,E,F,G
const byte numeri[6][7] = {
// 1
{0,1,1,0,0,0,0},
// 2
{1,1,0,1,1,0,1},
// 3
{1,1,1,1,0,0,1},
// 4
{0,1,1,0,0,1,1},
// 5
{1,0,1,1,0,1,1},
// 6
{1,0,1,1,1,1,1}
};
void setup() {
// Set segment pins as output
for (int i = 0; i < 7; i++) {
pinMode(segmenti[i], OUTPUT);
digitalWrite(segmenti[i], LOW); // turn off all segments at startup
}
// Set button pin as input
pinMode(pinPulsante, INPUT);
// Initialize random number generator by reading an unconnected analog pin (A0)
randomSeed(analogRead(A0));
}
void loop() {
// Read button state
int statoPulsante = digitalRead(pinPulsante);
if (statoPulsante == HIGH) { // button pressed
// Generate a random number from 1 to 6
int numero = random(1, 7);
// Display the number
mostraNumero(numero);
// Software debounce: wait 200 ms to avoid multiple reads
delay(200);
// Wait for button release before continuing
while (digitalRead(pinPulsante) == HIGH) {
delay(10);
}
}
}
// Function to light segments corresponding to number n (1-6)
void mostraNumero(int n) {
if (n < 1 || n > 6) return; // invalid number
for (int i = 0; i < 7; i++) {
if (numeri[n - 1][i] == 1) {
digitalWrite(segmenti[i], HIGH); // turn on segment
} else {
digitalWrite(segmenti[i], LOW); // turn off segment
}
}
}Arduino Uno (or compatible)
Common cathode 7-segment display
Momentary push button
220 ohm resistors for the display segments
10k ohm resistor for the button (pull-down)
Connecting wires
Breadboard
Arduino Pinout: