Hello,
I am trying to get the buzzer to buzz to match the results of the Dice result on the LCD screen. For example, I hold down the button, the dice runs through numbers 1-6, when i release the button a number will display on the LCD screen at random. The issue I am having is trying to get the buzzer to buzz to match the result on the LCD screen. For example, if i roll a 6, i want the buzzer to buzz 6 times. Then i hold the button and roll again, if i role a 3 i want to buzzer to buzz 3 times and so on. I have the current code so far, can someone help please?
This code rolls the dice (constantly runs through numbers 1-6 whilst pressed) and then displays a random result on the LCD screen.
I have used pin 15 (analogue input) for the buzzer and turned it into an output.
// Arduino Dice Roller on Wokwi Arduino Simulator
//Resistors are omitted. wires are hidden for simplicity
#include <LiquidCrystal.h>
#define BUTTON_PIN A0
const byte die1Pins[] = { 2, 3, 4, 5, 6, 7, 8};
const int rs = 12, en = 11, d4 = 10, d5 = 9, d6 = 13, d7 = 1;
LiquidCrystal lcd(rs,en,d4,d5,d6,d7);
int buzzer = 15;
void setup() {
lcd.begin(16,2);
lcd.setCursor(3,0);
lcd.print("Welcome to");
lcd.setCursor(2,1);
lcd.print("The Dice Game!");
delay(2000);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Hold the button");
lcd.setCursor(0,1);
lcd.print("to roll the dice!");
delay(2000);
lcd.clear();
pinMode(A0, INPUT_PULLUP);
pinMode (buzzer, OUTPUT);
for (byte i = 0; i < 7; i++) {
pinMode(die1Pins[i], OUTPUT);
}
}
void displayNumber(const byte pins[], byte number) {
digitalWrite(pins[0], number > 1 ? HIGH : LOW); // top-left
digitalWrite(pins[1], number > 3 ? HIGH : LOW); // top-right
digitalWrite(pins[2], number == 6 ? HIGH : LOW); // middle-left
digitalWrite(pins[3], number % 2 == 1 ? HIGH : LOW); // center
digitalWrite(pins[4], number == 6 ? HIGH : LOW); // middle-right
digitalWrite(pins[5], number > 3 ? HIGH : LOW); // bottom-left
digitalWrite(pins[6], number > 1 ? HIGH : LOW); // bottom-right
}
bool randomReady = false;
void loop(){
bool buttonPressed = digitalRead(BUTTON_PIN) == LOW;
bool buttonNotPressed = digitalRead(BUTTON_PIN) == HIGH;
if(!randomReady && buttonPressed) {
// to initialize the random number generator
randomSeed(micros());
randomReady = true;
}
if(buttonPressed) {
for (byte i = 0; i < 10; i++) {
int num1 = random(1, 7);
displayNumber(die1Pins, num1);
delay(50 + i * 20);
lcd.setCursor(4,0);
lcd.print("Rolling!");
lcd.setCursor(7,1);
lcd.print(num1);
}
}
if(buttonNotPressed && randomReady) {
lcd.setCursor(4,0);
lcd.print("!Winner!");
delay(750);
lcd.setCursor(4,0);
lcd.print(" ");
lcd.setCursor(4,0);
lcd.print("!Winner!");
delay(750);
lcd.setCursor(4,0);
lcd.print(" ");
lcd.setCursor(2,0);
lcd.print("!Roll Again!");
delay(1000);
lcd.setCursor(0,0);
lcd.print(" ");
}
}