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?

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
    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. – Edgar Bonet Aug 28 '17 at 9:09
0

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;
    }
  }
}
  • And I need to put this code at the beginning of loop()..? – Sonali_B Nov 13 '17 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, privacy policy and cookie policy

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