// ATtiny85 Output
// Entrada e Saída – Dado eletrônico
// https://wokwi.com/projects/291779699024069128
#include <LedControl.h>
#include <SoftwareSerial.h>
#define F_CPU 16500000L
#define CS_PIN PB0
#define CLK_PIN PB1
#define DIN_PIN PB2
#define BTN_PIN PB4
#define RND_PIN A0
#define SERIAL_TX PB3
#define SERIAL_RX PB5
#define MAX_SEG 1
// Sets the binary patterns for each number on the die (1 to 6)
uint8_t dice[7][8] = {
{ B00000000, B00000000, B00000000, B00000000, B00000000, B00000000, B00000000, B00000000 }, // Zero
{ B00000000, B00000000, B00000000, B00011000, B00011000, B00000000, B00000000, B00000000 }, // Um
{ B00000000, B01100000, B01100000, B00000000, B00000000, B00000110, B00000110, B00000000 }, // Dois
{ B11000000, B11000000, B00000000, B00011000, B00011000, B00000000, B00000011, B00000011 }, // Três
{ B00000000, B01100110, B01100110, B00000000, B00000000, B01100110, B01100110, B00000000 }, // Quatro
{ B11000011, B11000011, B00000000, B00011000, B00011000, B00000000, B11000011, B11000011 }, // Cinco
{ B00000000, B11011011, B11011011, B00000000, B00000000, B11011011, B11011011, B00000000 } // Seis
};
// Sets the serial pins
SoftwareSerial mySerial(SERIAL_RX, SERIAL_TX);
// Sets the pins of the LED array
LedControl mat = LedControl(DIN_PIN, CLK_PIN, CS_PIN, MAX_SEG); // MAX7219
bool waitDice = false;
uint8_t numberDice = 0;
void setup() {
mySerial.begin(9600);
mySerial.println("Click the button to roll the dice...");
pinMode(BTN_PIN, INPUT_PULLUP);
mat.shutdown(0, false);
// So that random doesn't repeat the sequence
// Not used. Used button press.
// randomSeed(analogRead(RND_PIN));
// Adjusts the brightness of the LED array to medium intensity
mat.setIntensity(0, 7);
// Cleans the display
mat.clearDisplay(0);
}
void showDice(uint8_t number) {
// Scroll through the matrix and set the number
for (uint8_t i = 0; i <= 7; i++) {
mat.setRow(0, i, dice[number][i]);
}
}
bool firstTime = true;
void rollsDice() {
int rollingTime = random(10, 15);
if (firstTime) { // Generate seed at first button press
mySerial.println(micros());
randomSeed(micros());
firstTime = false;
}
for (uint8_t i = 0; i < rollingTime; i++) {
// The number variable will take a value between 1 and 6
numberDice = random(1, 7);
showDice(numberDice);
mySerial.print(numberDice);
mySerial.print(" ");
delay(100 + i * 10);
}
showDice(0);
delay(500);
showDice(numberDice);
delay(250);
mySerial.print("=> ");
mySerial.println(numberDice);
waitDice = false; // Release the button to play again
}
void loop() {
// Checks button press
if (!digitalRead(BTN_PIN) && !waitDice) {
waitDice = true; // Locks the button until the end of the scroll
rollsDice(); // Roll the dice
}
}