Note

Hello, welcome to the SunFounder Raspberry Pi & Arduino & ESP32 Enthusiasts Community on Facebook! Dive deeper into Raspberry Pi, Arduino, and ESP32 with fellow enthusiasts.

Why Join?

  • Expert Support: Solve post-sale issues and technical challenges with help from our community and team.

  • Learn & Share: Exchange tips and tutorials to enhance your skills.

  • Exclusive Previews: Get early access to new product announcements and sneak peeks.

  • Special Discounts: Enjoy exclusive discounts on our newest products.

  • Festive Promotions and Giveaways: Take part in giveaways and holiday promotions.

👉 Ready to explore and create with us? Click [here] and join today!

Lesson 44: Digital Dice

This program simulates a dice roll using an OLED display. The simulation is triggered by shaking the vibration switch, causing the display to cycle through numbers 1 to 6, akin to rolling a dice. The display halts after a short duration, revealing a randomly selected number that represents the dice roll outcome.

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

Universal Maker Sensor Kit

94

Universal Maker Sensor Kit

You can also buy them separately from the links below.

Component Introduction

Purchase Link

Arduino UNO R3 or R4

BUY

Vibration Sensor Module (SW-420)

BUY

OLED Display Module (SSD1306)

-

Breadboard

BUY

Wiring

../_images/Lesson_44_Digital_dice_uno_bb.png

Code

Note

To install the library, use the Arduino Library Manager and search for “Adafruit SSD1306” and “Adafruit GFX” and install it.

Code Analysis

A comprehensive breakdown of the code:

  1. Initialization of variables:

    vibPin: Digital pin connected to the vibration sensor.

  2. Volatile variables:

    rolling: A volatile flag that indicates the dice’s rolling status. It is volatile as it is accessed within both the interrupt service routine and the main program.

  3. setup():

    Configures the vibration sensor’s input mode. Assigns an interrupt to the sensor to trigger the rollDice function upon state change. Initializes the OLED display.

  4. loop():

    Continuously checks if rolling is true, displaying a random number between 1 and 6 during this state. The rolling ceases if the sensor has been shaken for over 500 milliseconds.

  5. rollDice():

    The interrupt service routine for the vibration sensor. It initiates the dice roll when the sensor is shaken by recording the current time.

  6. displayNumber():

    Displays a selected number on the OLED screen.