/*
  Electronic Dice
  AnonEngineering 1/22/25
*/

#include <LedControl.h>

const int NUM_DEVICES = 2;
const int DATA_PIN = 3;
const int CS_PIN   = 4;
const int CLK_PIN  = 5;
const int BTN_PIN  = 6;
const byte die_faces[6][8] = {
  {B00000000, B00000000, B00000000, B00011000, B00011000, B00000000, B00000000, B00000000},
  {B00000011, B00000011, B00000000, B00000000, B00000000, B00000000, B11000000, B11000000},
  {B00000011, B00000011, B00000000, B00011000, B00011000, B00000000, B11000000, B11000000},
  {B11000011, B11000011, B00000000, B00000000, B00000000, B00000000, B11000011, B11000011},
  {B11000011, B11000011, B00000000, B00011000, B00011000, B00000000, B11000011, B11000011},
  {B11000011, B11000011, B00000000, B11000011, B11000011, B00000000, B11000011, B11000011}
};

LedControl lc = LedControl(DATA_PIN, CLK_PIN, CS_PIN, NUM_DEVICES);

bool checkButton()  {
  static bool oldBtnState = HIGH;

  bool isPressed = false;
  int btnState = digitalRead(BTN_PIN);
  if (btnState != oldBtnState)  {
    oldBtnState = btnState;
    if (btnState == LOW) {
      isPressed = true;
      //Serial.println(F("Button pressed"));
    }
    delay(20);  // debounce
  }
  return isPressed;
}

void doSpin() {
  for (int speed = 50; speed <= 150; speed += 25)  {
    for (int count = 0; count < 6; count++) {
      for (int row = 0; row < 8; row++) {
        lc.setRow(1, row, die_faces[count][row]);
        lc.setRow(0, row, die_faces[5 - count][row]);
      }
      delay(speed);
    }
  }
}

void drawDice(int die1, int die2) {
  doSpin();
  Serial.print("Die 1: ");
  Serial.print(die1 + 1);
  Serial.print("\tDie 2: ");
  Serial.println(die2 + 1);
  for (int row = 0; row < 8; row++) {
    lc.setRow(1, row, die_faces[die1][row]);
    lc.setRow(0, row, die_faces[die2][row]);
  }
}

void setup() {
  Serial.begin(115200);
  randomSeed(analogRead(A0));
  pinMode(BTN_PIN, INPUT_PULLUP);
  for (int i = 0; i < NUM_DEVICES; i++) {
    lc.shutdown(i, false);
    lc.setIntensity(i, 8);
  }
  Serial.println(F("Press the button to roll!\n"));
}

void loop() {
  if (checkButton())  {
    int die1 = random(6);
    int die2 = random(6);
    drawDice(die1, die2);
  }
}