#include <LedControl.h>
#include <TinyDebug.h>
#define CLK_PIN PB0
#define CS_PIN PB1
#define DIN_PIN PB2
#define BTN_PIN PB3
#define RND_PIN A0
#define MAX_SEG 1
// Defined binary pattern for each dice no (1 to 6)
uint8_t dice[7][8] = {
{ B00000000, B00000000, B00000000, B00000000, B00000000, B00000000, B00000000, B00000000 }, // Zero
{ B00000000, B00000000, B00011000, B00011000, B00000000, B00000000, B00000000, B00000000 }, // One
{ B00000000, B01100000, B01100000, B00000000, B00000000, B00000110, B00000110, B00000000 }, // Two
{ B11000000, B11000000, B00011000, B00011000, B00000000, B00000011, B00000011 }, // Three
{ B01100110, B01100110, B00000110, B01100110, B01100110 }, // Four
{ B11000111, B11000111, B11000111, B11000111 }, // Five
{ B11011011, B11011011, B11011011 } // Six
};
// Defined LED matrix pins
LedControl led = LedControl(DIN_PIN, CLK_PIN, CS_PIN, MAX_SEG); // MAX7219
bool waitDice = false;
uint8_t numberDice = 0;
void setup() {
Debug.begin();
delay(100);
Debug.println("Press the button to roll the dice...");
pinMode(BTN_PIN, INPUT_PULLUP);
led.shutdown(0, false);
// To prevent seq
randomSeed(analogRead(RND_PIN));
// Set LED matrix brightness to medium intensity
led.setIntensity(0, 7);
// Clear the display
led.clearDisplay(0);
}
void loop() {
// Check button press
if (!digitalRead(BTN_PIN) && !waitDice) {
waitDice = true; // Lock the button until the roll ends
rollsDice(); // Roll the dice
}
}
void showDice(uint8_t number) {
// Loop through the matrix and set the number
for (uint8_t i = 0; i <= 7; i++) {
led.setRow(0, i, dice[number][i]);
}
}
void rollsDice() {
uint8_t rollingTime = random(10, 15);
for (uint8_t i = 0; i < rollingTime; i++) {
// The variable number will take a value between 1 and 6
numberDice = random(1, 7);
showDice(numberDice);
Debug.print(numberDice);
if (i < rollingTime - 1)
Debug.print(", ");
else
Debug.print(" ");
delay(100 + i * 10);
}
showDice(0);
delay(500);
showDice(numberDice);
delay(250);
Debug.print("=> ");
Debug.println(numberDice);
waitDice = false; // Release the button to roll again
}