I'll like to code for a game, and it'll come with a stop option that allows the player to exit/restart the game.
How should I code for that stop button? Do I put it in a separate while loop under the void loop?
I'll like to code for a game, and it'll come with a stop option that allows the player to exit/restart the game.
How should I code for that stop button? Do I put it in a separate while loop under the void loop?
One of the easiest ways to restart your game is to use the inbuilt reset line. The Arduino Uno/Due/M0/101 has a physical reset button next to the USB connector. For some of the other baords like the Arduino Mega, it is closer to the chip in the middle of the board.
The reset line is held high by a pull up resistor. This button shorts the reset pin to Gnd, resetting the microcontroller.
Once reset, the microcontroller starts up again as if it has just been powered on. This has the advantage of saving on adding code to handle the game being reset.
There are lots of possible approaches. One possibility would be to set up your code something like this:
enum { STOPPED, PLAYING } flag;
void setup() {
// setup stuff ...
flag = STOPPED;
}
void loop() {
while (flag == STOPPED)
{
// wait for start button
if (start button pressed)
{
// initialise the game ...
flag = PLAYING;
}
}
while (flag == PLAYING)
{
// play the game
if (stop button pressed)
{
flag = STOPPED;
}
}
}
If you code your loop without delay() or busy loops then it is pretty easy:
void loop(){
if(DigitalRead(RESET_BUTTON)){
// Reinitialize game state
}
//rest of game logic.
}