/*
MSJ Researchers World
Date - 3rd DEC 2024
Mentor - Mr. Siranjeevi M
Contact - 7373771991
*/
// Pin definitions
const int buttonPin = 11; // Push button connected to pin 11
const int ledPins[] = {4, 5, 6, 7, 8, 9, 10}; // Pins for 7 LEDs to represent dice faces
int buttonState = 0; // Variable for button state
int lastButtonState = 0; // Variable for storing the last button state
int randomNumber = 0; // Store the random dice number
void setup() {
// Initialize Serial Monitor
Serial.begin(9600);
// Initialize the button pin as input
pinMode(buttonPin, INPUT_PULLUP);
// Initialize the LED pins
for (int i = 0; i < 7; i++) {
pinMode(ledPins[i], OUTPUT);
}
// Welcome message
Serial.println("Digital Dice: Press the button to roll the dice!");
}
void loop() {
// Read the button state
buttonState = digitalRead(buttonPin);
// Check if the button is pressed (LOW because we use internal pull-up)
if (buttonState == LOW && lastButtonState == HIGH) {
// Button was pressed, generate a random number between 1 and 6
randomNumber = random(1, 7);
// Show the corresponding dice face
displayDice(randomNumber);
// Print the result to the Serial Monitor
Serial.print("Dice rolled: ");
Serial.println(randomNumber);
delay(200); // Delay for debouncing
}
// Save the current button state for the next loop
lastButtonState = buttonState;
}
void displayDice(int number) {
// Turn off all LEDs
for (int i = 0; i < 7; i++) {
digitalWrite(ledPins[i], LOW);
}
// Display the corresponding face using LEDs
switch (number) {
case 1:
digitalWrite(ledPins[3], HIGH); // Middle LED
break;
case 2:
digitalWrite(ledPins[0], HIGH); // Top-left LED
digitalWrite(ledPins[6], HIGH); // Bottom-right LED
break;
case 3:
digitalWrite(ledPins[0], HIGH); // Top-left LED
digitalWrite(ledPins[3], HIGH); // Middle LED
digitalWrite(ledPins[6], HIGH); // Bottom-right LED
break;
case 4:
digitalWrite(ledPins[0], HIGH); // Top-left LED
digitalWrite(ledPins[1], HIGH); // Top-right LED
digitalWrite(ledPins[5], HIGH); // Bottom-left LED
digitalWrite(ledPins[6], HIGH); // Bottom-right LED
break;
case 5:
digitalWrite(ledPins[0], HIGH); // Top-left LED
digitalWrite(ledPins[1], HIGH); // Top-right LED
digitalWrite(ledPins[3], HIGH); // Middle LED
digitalWrite(ledPins[5], HIGH); // Bottom-left LED
digitalWrite(ledPins[6], HIGH); // Bottom-right LED
break;
case 6:
digitalWrite(ledPins[0], HIGH); // Top-left LED
digitalWrite(ledPins[1], HIGH); // Top-right LED
digitalWrite(ledPins[2], HIGH); // Top-middle LED
digitalWrite(ledPins[4], HIGH); // Bottom-middle LED
digitalWrite(ledPins[5], HIGH); // Bottom-left LED
digitalWrite(ledPins[6], HIGH); // Bottom-right LED
break;
}
}