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 |
You can also buy them separately from the links below.
Component Introduction |
Purchase Link |
|---|---|
Arduino UNO R3 or R4 |
|
- |
|
Wiring
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:
Initialization of variables:
vibPin: Digital pin connected to the vibration sensor.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.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.
loop():Continuously checks if
rollingis 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.rollDice():The interrupt service routine for the vibration sensor. It initiates the dice roll when the sensor is shaken by recording the current time.
displayNumber():Displays a selected number on the OLED screen.