Hi, This is my idea, you have a quiz master and 4 gamers, each have a button including the quiz master. the quiz master asks a question the first gamer to press their button cancels the other gamers buttons and plays a sound(each button will have a differnt sound and coloured light).
when the quiz master is ready to ask the next question he/she presses their button to clear all the varibles for the button press loop to start again…….
Now!!! althought i have written a few programes for the arduino I’m ONLY a BEGINNER…..
I have no idea how to check for a button press, how to power a bulb in the button…
So my first call for help is to check for a button press. i want to try the programming on my own, i have a fair idea of how i’m going to write it, i just need to know the button press help at the moment.
I thank you ALL in advance and look forward to your replies….
This sounds like it would be a good use of STATES. For example, your logic could have one STATE, with two options: OPEN and SOLVED.
When State=SOLVED, no contestant buttons have any function. Only the GM’s button works (to reset the State=OPEN).
When State=OPEN, the first contestant to push their button would change the state to SOLVED (thus preventing any other contestant’s button from having any action). And only the contestant who pushed their button when State=OPEN would get the sounds/light.
Here is an old Jeopardy style game sketch from a few years back.
You can modify it as you need.
Ask questions on those things you do not understand.
//
//================================================^================================================
// J e o p a r d y S t y l e G a m e
//================================================^================================================
//
// URL
//
// LarryD
//
// Version YY/MM/DD Comments
// ======= ======== ========================================================================
// 1.00 23/01/14 Running code
//
//
//
//
// Notes:
// Jeopardy style game.
// A (masterSwitch) will enable 4 (gameSwitches) to "buzz" in.
// Once a contestant switch is pressed, the other contestants are locked out, winner's corresponding LED is lit.
// The loop resets after 5 seconds and waits for the master switch to be pressed again.
//
//
//======================
//Macros
#define LEDon HIGH
#define LEDoff LOW
#define PRESSED LOW
#define RELEASED HIGH
#define ENABLED true
#define DISABLED false
//======================
//GPIOs
const byte heartbeatLED = 13; //We toggle this LED every 500ms to check for program action.
const byte masterSwitch = 11;
const byte gameStartLED = 6; //Comes ON when the master has pressed the masterSwitch.
//index 0 1 2 3
const byte gameSwitch[] = { 7, 8, 9, 10}; //Contestant switch pins.
const byte gameLED[] = { 2, 3, 4, 5}; //Contestant LED pins.
const byte switchCount = sizeof(gameSwitch); //Number of contestant switches.
//======================
//Variables
bool onFlag = DISABLED; //DISABLED = not in 5 second timing mode.
bool polingFlag = DISABLED; //DISABLED = not scanning the contestant switches.
//======================
//Timing stuff.
const unsigned long heartbeatInterval = 500ul; //Toggle heartbeatLED every 500 milliseconds.
unsigned long heartbeatTime;
const unsigned long switchInterval = 25ul; //Check switches every 25 milliseconds.
unsigned long switchesTime;
const unsigned long onInterval = 5000ul; //After you have a winner leave LED on for this time.
unsigned long onTime;
// s e t u p ( )
//================================================^================================================
//
void setup()
{
pinMode(heartbeatLED, OUTPUT);
pinMode(masterSwitch, INPUT_PULLUP);
pinMode(gameStartLED, OUTPUT);
digitalWrite(gameStartLED, LEDoff);
//======================
//Initialize contestant switches and LEDs.
for (int i = 0; i < switchCount; i++)
{
pinMode(gameSwitch[i], INPUT_PULLUP);
pinMode(gameLED[i], OUTPUT);
digitalWrite(gameLED[i], LEDoff);
}
//======================
//Gives a visual indication if the LEDs are working.
//Lamp test, flash LEDs 10 times at reset, an even number leaves the LEDs off.
for (int x = 0; x < 20; x++)
{
for (int i = 0; i < switchCount; i++)
{
//Toggle this LED.
digitalWrite(gameLED[i], !digitalRead(gameLED[i]));
}
//Toggle this LED.
digitalWrite(gameStartLED, !digitalRead(gameStartLED));
delay(500);
}
} //END of setup()
// l o o p ( )
//================================================^================================================
//
void loop()
{
//======================================================================== T I M E R heartbeat
//Is it time to toggle the heartbeat LED ?
if (millis() - heartbeatTime >= heartbeatInterval)
{
//Restart this TIMER.
heartbeatTime = millis();
//toggle the heartbeat LED
digitalWrite(heartbeatLED, digitalRead(heartbeatLED) == HIGH ? LOW : HIGH);
}
//======================================================================== T I M E R switches
//Is it time to scan the switches ?
if (millis() - switchesTime >= switchInterval)
{
//Restart this TIMER.
switchesTime = millis();
checkSwitches();
}
//======================================================================== T I M E R fiveSecond
//Are we in the 5 second timeout ?
if (onFlag == ENABLED && millis() - onTime >= onInterval)
{
//Disable this TIMER.
onFlag = DISABLED;
//======================
//Turn off contestant LEDs.
for (int i = 0; i < switchCount; i++)
{
digitalWrite (gameLED[i], LEDoff) ;
}
}
//================================================
// Other non blocking code goes here
//================================================
} // END of loop()
// c h e c k S w i t c h e s ( )
//================================================^================================================
//
void checkSwitches()
{
//======================
//If we are not polling the contestant switches, has the master switch been pressed?
if (polingFlag == DISABLED && digitalRead(masterSwitch) == PRESSED)
{
//LED goes ON when the game starts.
digitalWrite (gameStartLED, LEDon);
//Turn off contestant LEDs.
for (int i = 0; i < switchCount; i++)
{
digitalWrite (gameLED[i], LEDoff);
}
//Enable contestant switch scanning.
polingFlag = ENABLED;
}
//======================
//Are we allowed to scan for a winner ?
if (polingFlag == ENABLED)
{
//Scan for a contestant switch press.
for (int i = 0; i < switchCount; i++)
{
//Is this switch pressed ?
if (digitalRead(gameSwitch[i]) == PRESSED)
{
//Turn on the contestant winner LED.
digitalWrite (gameLED[i], LEDon);
//Disable further scanning; allows the master to start a new game.
polingFlag = DISABLED;
//Initialize the game LED.
digitalWrite (gameStartLED, LEDoff);
//Enable the 5 second countdown timer.
onFlag = ENABLED;
//Restart this TIMER.
onTime = millis();
//We found a winner, stop looking any further.
break;
}
}
} //END of if (polingFlag == true)
} // END of checkSwitches()
//
//================================================^================================================
//
I would recommend using a DFplayer mini for this. They are very cheap. You can have whatever and as many sounds as you need. Using your PC/laptop, get the sounds into MP3 format files and copy them to a micro-SD card. Put the SD card into the DFplayer. Connect up the player to the Arduino and the Arduino can send commands to it to play the required file at any time. The DFplayer can directly drive a small speaker and is quite loud. But if you need more volume you can connect a pair of powered speakers instead.
Here is an example how you could handle four player and one master button:
/*
Forum: https://forum.arduino.cc/t/check-for-4-buttons-being-pressed-when-1-button-pressed-cancel-other-3/1424266
Wokwi: https://wokwi.com/projects/452690693128804353
ec2021
Example for reading four buttons after being released by one
master button (black)
The sketch uses a button class that can be used for bouncing
buttons, however in this specific case debounceTime is set to
zero as each button press (master or player) changes the state
of the state machine so that any bouncing becomes irrelevant.
BtnClass provides the ability to read the press time in millis()
so that even very close presses of buttons can be evaluated
down to the millisecond (while having two buttons pressed that
close is very unlikely). However this feature allows to calculate
the time between the release by the master button and the player's
reaction.
*/
constexpr unsigned long debounceTime {0};
constexpr byte ledPin {9};
constexpr byte masterPin {8};
constexpr byte playerPin[] {2, 3, 4, 5};
constexpr int players = sizeof(playerPin) / sizeof(playerPin[0]);
enum class GAME {IDLE, PLAY, FINISHED};
GAME state = GAME::IDLE;
class BtnClass {
private:
byte pin;
byte state;
byte lastState;
unsigned long lastChange;
unsigned long lastPressTime;
public:
init(byte p) {
pin = p;
pinMode(pin, INPUT_PULLUP);
lastPressTime = 0;
}
unsigned long getLastPressTime() {
return lastPressTime;
};
void reset() {
lastPressTime = 0;
}
boolean pressed() {
byte actState = digitalRead(pin);
if (actState != lastState) {
lastChange = millis();
lastState = actState;
};
if (actState != state && millis() - lastChange > debounceTime) {
state = actState;
if (!state) lastPressTime = lastChange;
return !state;
}
return false;
}
};
BtnClass master;
BtnClass player[players];
void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
master.init(masterPin);
for (int i = 0; i < players; i++) {
player[i].init(playerPin[i]);
}
}
void loop() {
stateMachine();
}
void stateMachine() {
switch (state) {
case GAME::IDLE:
if (master.pressed()) {
digitalWrite(ledPin, HIGH);
state = GAME::PLAY;
for (int i = 0; i < players; i++) {
player[i].reset();
}
}
break;
case GAME::PLAY:
for (int i = 0; i < players; i++) {
if (player[i].pressed()) {
digitalWrite(ledPin, LOW);
state = GAME::FINISHED;
}
}
break;
case GAME::FINISHED:
for (int i = 0; i < players; i++) {
if (player[i].getLastPressTime() > 0) {
Serial.print("Player ");
Serial.print(i + 1);
Serial.print(" pressed after ");
Serial.println(player[i].getLastPressTime() - master.getLastPressTime());
}
}
state = GAME::IDLE;
break;
}
}
You have shown excellent enthusiasm, and hopefully you willl be able to commplete your project if you follow SSS (Start with Small Step) strategy.
A: I would like to make a simple structure of your game as follows just to srart with:
1. Game Master holds down his button M; all LEDs are On, all buttons are inactive, and buzzer is Off.
2. Master places the question on the screen from his PC.
3. Master releases his button, all LEDs are Off, buzzer is Off, buttons G1-G4 are active, and 20 sec time slot begins within which a game player must press his button indicating his intention to answer.
4. When a game player presses his button, the corresponding LED turns On, buzzer makes 3 sec tone, and disables buttons of other game players.
5. Game player selects his answer out-of-3 options. This part of game will be added later.
6. Master presses his button, everything goes to intial states and Master presents the next question.
B: Connet five buttons, five LEDS, and a buzzer as per Fig-1 with your Arduino UNO R3. As each button is terminated by internal pull-up resistor, you don't need any other external resistor to connect with the buttons. Place series resistors with the LEDs and buzzer.
1. Create a test sketch/program so that whenever you press any buton, the corresponding LED (M-RLD, G1-GLD, ...) becomes On and the buzeer makes a tone for 3 sec. Save sketh as test1 under your workig folder.
2. How to know/check that a button (say: M) has been pressed/closed?
The button M is in the open condition. If you have a DVM, connect it between DPin-2 and GND; you will observe a reading very close to 5 V (HIGH = 1). This 5 V appears on DPin-2 from the 5 V supply through Rip (the internal pull-up resistor).
When you press the M button, the DVM reading drops to approx. 0 V (LOW = 0) indicating that DPin-2 is shorted to the GND pin. The pull-up resistor prevents the 5 V supply from being directly shorted to ground.
Now, you write codes to tell the MCU for reading the logic level of DPin-2 and checks for a LOW level to determine that M is closed and then turn on RLD led and activate buzzer for 3 sec tone.
3. Now save test1 program as test2 and do modifications as necessary so that your program behaves like this:
(1) Press G1 button, and check that GLD and buzzer are active. Press G2 to G4, and observe that nothing happens -- means the corresponding LEDs do not turn On and the buzzer is also inactive.
(2) next what .....?
Whatever thoughts and their interconnections you have accumulated in your mind/brain regarding the solution of your gaming problem, try to put them on paper by a Flow Chart which is created using the following geometrical figures (Fig-2).
Begin with a basic (simple and elemetary) Flow Chart (Fig-3) and then keep modifying it as the complexities/tasks come in. Conversion of the Flow Chart into Programming Codes would be an interesting exercise.
C: The Game Description 1. The Game Master (GM) presses and holds the M button. While the button is held, all LEDs are ON and the buzzer is OFF.
2. When the GM releases the M button, all LEDs turn OFF, the buzzer remains OFF, and a 20-second time window starts. Within this time window, any one of the four Game Players (GPs) may press his button.
3. When a GP presses his button within the allowed time:
his LED turns ON,
the buzzer is activated for 3 seconds using the tone() function, and
all remaining GPs are locked out (their button presses are ignored).
4. After this, the GM starts the next round of the game.
OP has said that each button is associated with a LED and a common buzzer. Your example contains only one LED instead of five and no buzzer. Can you please add those missing components in your Wokwi schematic and add necessary codes in your class based sketch?
Let us wait to see how OP reacts to our posts. In the meantime, I would like to digest your class based sketch in order to help OP in need as your second hand.
Maybe add a class member that is used to determine if the pull-up should be turned ON.
It is also used to check if the user’s switch is pressed.
Here is a simple structure I use when introducing stucts.
// S T R U C T U R E S
//================================================^================================================
//
//This sketch intentionally avoids discussing advanced structures and classes.
//
//This struct (structure) automates the process of making simple "Switch Input Objects".
//The struct below has 4 data members and 1 member function.
//
struct createSwitchInput
{
byte pin; //.pin The GPIO pin this switch is connected to.
byte pressedState; //.pressedState The pin state when the switch is pressed.
byte lastState; //.lastState The "state" the switch was last in.
unsigned long pressTime; //.pressedTime The time when the switch was pressed.
//Constructor
createSwitchInput(byte _pin, byte _pressedState)
{
pin = _pin;
pressedState = _pressedState;
lastState = digitalRead(pin);
pressTime = millis();
//Do we need to enable the internal pull-up resistor ?
if (pressedState == LOW)
{
pinMode(pin, INPUT_PULLUP);
}
}
}; //END of struct
//========================
//Create and initialize our "Switch Input Objects".
//Example:
//createSwitchInput startSwitch = {7, LOW};
//Creates the "startSwitch" object. This switch is connected to pin 7, when pressed, the input is LOW.
//We have access to: startSwitch.pin, startSwitch.pressedState, startSwitch.lastState, and startSwitch.pressedTime
//
createSwitchInput redSwitch = {switchOne, LOW}; //.pin .pressedState
createSwitchInput relaySwitch = {switchTwo, LOW}; //.pin .pressedState
In BtnClass pinMode() is set in the init() function which is called in setup().
It would be possible to e.g. add different init() calls where the choice finally determines whether the internal pull-up is required and also whether the pressed() function reacts on LOW or HIGH...
First off let me apologise for my late response. I have been reading your reply’s from my phone via emails, but unfortunatly I haven’t been able to get to my laptop to reply.
Well! what can I say? I’m TOTALLY overwhelmed by everyone’s responses, THANK YOU ALL.
I have to be perfectly honest, I’ve looked at the programs and the symantic’s and can Honestly say I never expected it to be (or appear to be) so difficult. the program’s are using commands I’ve never heard of before, like wise the symantics although I can follow them are using components I haven’t used.
That said I do intend to study ALL your responses, but it will take time because I will read them and take them apart and try to work out what each part is doing and how it’s doing it by looking things up, (hope that makes sense).
I DO intend to purchass the Arduino Cook book asap. I do have a book called “Programing Arduino: Getting started with Sketches”.
I don’t want this to sound ungrateful, but I beleive the best way to learn is to try yourself, copying in my opion does not stick in your mind and you’re never sure has how somethings work.
Is it possible for someone to tell me how to print the post’s you’ve sent? I want to study the programs. i want to print them off so i can make notes on them.
I’m not even sure I’m posting this reply in the right place, if by some chance it IS in the wrong place. could someone kindly put it where it should be.
Don't forget to purchase Arduino UNO R3, nice buttons, LEDs, resistors, passive buzzer, breadboatd, and dupont jumpers.
If you like the Flow Chart that I have posted, then it will be apple pie for you to learn and remember all kinds of programming constructs regardless how cryptic they are.
This is so true, you learn programming by programming.
We never suggest you blindly copy code.
Looking at what others have done and fully understanding what is offered is a good way of building from others’ skills.
Incorporating elements from others is a good way of becoming proficient.
When new user starts out, it is recommended they go through the IDE examples.
This includes examples that more experienced users offer.
If my room light burns out I don’t need to melt glass, make a filament and assemble a DIY light bulb.
I purchase a new one.
I don’t understand how the C++ compiler works, how the code is placed in the controller or how that RTC functions.
I do need to know how to use tools, libraries and techniques that others have already sweated over.
By all means, the more you do the more you can do.
We often urge people to forget about using blocking code as it makes a project unresponsive.
Avoid using delay(. . .) , time consuming while(. . .) loops, spaghetti code using goto .
Learn how to make non-blocking TIMERs using the millis or micros function. Learn about program flags.
Learn how to use a State Machine. Learn about switch de-bouncing. Learn to examine switches for a change in state rather a switch’s current state.
Learn how to use arrays. Learn about structs and classes. Learn . . .