Im making a buzzer box (Think family feud) and I would like to be able to set a timer in the background while contestants play, if the timer hits zero, the buzzers lock and the code restarts. Another problem is that I would like to have the box auto reset, but I can't find a way. Any help would be appreciated.
Here's the code (Im using a Nano):
void setup() {
pinMode(Win LED 1, OUTPUT); pinMode(Buzzer 1, INPUT_PULLUP);
pinMode(Buzzer 2, INPUT_PULLUP);
pinMode(Win LED 2, OUTPUT); pinMode(Box Ready LED, OUTPUT);
}
void loop() {
digitalWrite(Box Ready LED, HIGH);
if (digitalRead(Buzzer 2) == LOW) {
exit(0);
}
else if (digitalRead(Buzzer 2) == HIGH) {
if (digitalRead(Buzzer 1) == LOW) {
digitalWrite(Win LED 1, HIGH);
}
if (digitalRead(Buzzer 1) == LOW) {
exit(0);
}
else if (digitalRead(Buzzer 1) == HIGH) {
if (digitalRead(Buzzer 2) == LOW) {
digitalWrite(Win LED 2, HIGH);
}
}
}
}
Note how much easier to read and follow than your version of the same code
My first suggestion would be to make the code even more readable by giving pins meaningful names rather than using anonymous pin numbers throughout the code
There’s a fundamental flaw in your code…
By using the delay(200), you’re guaranteeing that buzzer 1 will always win if both players press within 200mS of each other.(That’s a long time in buzzer games!’
Use millis timing, and test both inputs at the same time, then randomise the winner in the very rare case they are coincidental.
const int BuzzerCount = 2;
const byte WinLEDPins[BuzzerCount] = {5, 6};
const byte BuzzerButtonPins[BuzzerCount] = {2, 3};
const byte BoxReadyLEDPin = 4;
void setup()
{
for (int i = 0; i < BuzzerCount; i++)
{
digitalWrite(WinLEDPins[i], LOW); // LED off
pinMode(WinLEDPins[i], OUTPUT);
pinMode(BuzzerButtonPins[i], INPUT_PULLUP);
}
digitalWrite(BoxReadyLEDPin, LOW); // LED off
pinMode(BoxReadyLEDPin, OUTPUT);
}
void loop()
{
digitalWrite(BoxReadyLEDPin, HIGH);
random(10); // Just throw away a random number
// Check all of the buttons and select a winner
// if any button or buttons are pressed.
int winner = -1;
int winnerCount = 0;
for (int i = 0; i < BuzzerCount; i++)
{
if (digitalRead(BuzzerButtonPins[i]) == LOW)
{
if (winnerCount == 0)
{
// First winner!
winner = i;
winnerCount++;
}
else
{
// Another winner! What are the odds? (1 in winnerCount)
winnerCount++;
// Pick a random integer from 0 to winnerCount-1.
// If the number is 0, this winner replaces the
// previous winners
if (random(winnerCount) == 0)
winner = i;
}
}
}
// Do we have a winner this time?
if (winner != -1)
{
digitalWrite(WinLEDPins[winner], HIGH); // Light up the winner's LED
digitalWrite(BoxReadyLEDPin, LOW);
delay(5000);
digitalWrite(WinLEDPins[winner], LOW);
}
}