1

The code below is part of my "safe" program. I have to make 4 "guesses" (the password consists of 4 numbers). For each guess I use a few if statements but i was wondering if there is a way to make a method for each "guess". This way instead of these 4 sections of if-statements i would just have one Method.

if (turn == 1) {

    if ((buttonState != lastButtonState) && buttonState == 1) {
      guess1 = newValue;
      turn = 2;
      Printer();
    }
    lastButtonState = buttonState;
  }
  if (turn == 2) {
    if ((buttonState != lastButtonState) && buttonState == 1) {
      guess2 = newValue;
      turn = 3;
      Printer();
    }
    lastButtonState = buttonState;
  }

  if (turn == 3) {
    if ((buttonState != lastButtonState) && buttonState == 1) {
      guess3 = newValue;
      turn = 4;
      Printer();
    }
    lastButtonState = buttonState;
  }

  if (turn == 4) {
    if ((buttonState != lastButtonState) && buttonState == 1) {
      gok4 = nieuwewaarde;
      beurt = 5;
      Printer();
    }
    lastButtonState = buttonState;
  }
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 1
    Since Arduino is using C++ I removed the C tag. As for your problem, yes it is possible to break out the common code into a separate function. I would actually recommend it. For it to work I suggest you [find a good beginners book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and read a little bit about functions, and also about passing arguments *by reference*. – Some programmer dude Nov 18 '16 at 10:03

1 Answers1

0

Theoretically it should be possible to shrink it to something like this. Note you should use an array instead of a series of guess1, guess2, … variables.

int guess[4];

if ((buttonState != lastButtonState) && buttonState == 1) {
  guess[turn-1] = newValue;
  if (turn == 4)
  {
      gok4 = nieuwewaarde;
      beurt = 5;
  }
  else
      turn = turn+1;
  Printer();
}
lastButtonState = buttonState;

You can adjust the +1/-1 if you count turn from 0. But with a broader view of what you would like to achieve, there might be other ways to write things.

Besides, Arduino code is not in C++, but AVR. The “user” code is Processing.

Tom
  • 834
  • 1
  • 14
  • 24