6.2 Electronic Dice

Here we use button, 7-segment and 74hc595 to make an electronic dice. Each time the button is pressed, a random number ranging from 1 to 6 is generated and displayed on the 7-segment Display.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

3 in 1 Starter Kit

380+

3 in 1 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

SunFounder R3 Board

BUY

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

Button

BUY

74HC595

BUY

7-segment Display

BUY

Schematic

../_images/circuit_8.9_eeprom.png

Wiring

../_images/wiring_electronic_dice.png

Code

Note

  • Open the 6.2.electronic_dice.ino file under the path of 3in1-kit\basic_project\6.2.electronic_dice.

  • Or copy this code into Arduino IDE.

  • Or upload the code through the Arduino Web Editor.

When the code is uploaded successfully, the 7-segment Display will display 0-7 in a fast scroll, and when you press the button, it will display a random number and stop scrolling. The scrolling display starts again when you press the button again.

How it works?

This project is based on 5.10 ShiftOut(Segment Display) with a button to start/pause the scrolling display on the 7-segment Display.

  1. Initialize each pin and read the value of the button.

    void setup ()
    {
    
        ...
        attachInterrupt(digitalPinToInterrupt(buttonPin), rollDice, FALLING);
    }
    
    • The interrupt is used here to read the state of the button. The default value of buttonPin is low, which changes from low to high when the button is pressed.

    • rollDice represents the function to be called when the interrupt is triggered, it is used to toggle the value of the variable state.

    • FALLING means the interrupt is triggered when the buttonPin goes from low to high.

  2. When the variable state is 0, the function showNumber() is called to make the 7-segment Display randomly display a number between 1 and 7.

    void loop()
    {
        if (state == 0) {
            showNumber((int)random(1, 7));
            delay(50);
        }
    }
    
  3. About rollDice() function.

    void rollDice() {
        state = !state;
    }
    

    When this function is called, it toggles the value of state, such as 1 last time and 0 this time.

  4. About showNumber() function.

    void showNumber(int num) {
        digitalWrite(STcp, LOW); //ground ST_CP and hold low for as long as you are transmitting
        shiftOut(DS, SHcp, MSBFIRST, datArray[num]);
        //return the latch pin high to signal chip that it
        //no longer needs to listen for information
        digitalWrite(STcp, HIGH); //pull the ST_CPST_CP to save the data
    }
    

    This is the code inside loop() in the project 5.10 ShiftOut(Segment Display) into the function showNumber().