0

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?

1

3 Answers 3

2

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.

1
  • 1
    Note that the reset line is also available on a pin header, which can be handy if the OP prefers to wire his own button. Aug 28, 2017 at 9:09
1

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;
    }
  }
}
1
  • And I need to put this code at the beginning of loop()..?
    – Sonali_B
    Nov 13, 2017 at 6:52
0

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.

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.