Good Arduino Code

Dice Roller

A digital dice roller, controlled by Arduino. Each dice is represented by 7 LEDs that are arranged according to standard dice pip pattern.

There are two dice and one button. Pressing the button rolls the dice, displays a sequence of random numbers, followed by the result.

The LEDs are connected to the Arduino pins as follows:

LED pin connections

Hardware

ItemQuantityNotes
Arduino Uno R31
5mm LED14Red and Green
12mm Push button1
Resistor14220Ω

Diagram

diagram
Dice roller connection diagram

Pin Connections

Arduino PinPartLocation
2Red LEDTop-left
3Red LEDTop-right
4Red LEDMid-left
5Red LEDCenter
6Red LEDMid-right
7Red LEDBottom-left
8Red LEDBottom right
9Green LEDTop-left
10Green LEDTop-right
11Green LEDMid-left
12Green LEDCenter
A3Green LEDMid-right
A4Green LEDBottom-left
A5Green LEDBottom right
A0Button
  • The LEDs are connected through a 220Ω resistor each.

Video Tutorial

Source code

Download projectView on GitHub

dice-roller.ino

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
// Arduino Dice Roller
// Copyright (C) 2020, Uri Shaked

#define BUTTON_PIN A0

const byte die1Pins[] = { 2, 3, 4, 5, 6, 7, 8};
const byte die2Pins[] = { 9, 10, 11, 12, A3, A4, A5};

void setup() {
  pinMode(A0, INPUT_PULLUP);
  for (byte i = 0; i < 7; i++) {
    pinMode(die1Pins[i], OUTPUT);
    pinMode(die2Pins[i], OUTPUT);
  }
}

void displayNumber(const byte pins[], byte number) {
  digitalWrite(pins[0], number > 1 ? HIGH : LOW); // top-left
  digitalWrite(pins[1], number > 3 ? HIGH : LOW); // top-right
  digitalWrite(pins[2], number == 6 ? HIGH : LOW); // middle-left
  digitalWrite(pins[3], number % 2 == 1 ? HIGH : LOW); // center
  digitalWrite(pins[4], number == 6 ? HIGH : LOW); // middle-right
  digitalWrite(pins[5], number > 3 ? HIGH : LOW); // bottom-left
  digitalWrite(pins[6], number > 1 ? HIGH : LOW); // bottom-right
}

bool randomReady = false;

void loop() {
  bool buttonPressed = digitalRead(BUTTON_PIN) == LOW;
  if (!randomReady && buttonPressed) {
    /* Initialize the random number generator with the number of
       microseconds between program start and the first button press */
    randomSeed(micros());
    randomReady = true;
  }

  if (buttonPressed) {
    for (byte i = 0; i < 10; i++) {
      int num1 = random(1, 7);
      int num2 = random(1, 7);
      displayNumber(die1Pins, num1);
      displayNumber(die2Pins, num2);
      delay(50 + i * 20);
    }
  }
}

Simulation