One time execution of a variable incrementation As part of a larger script intended for a very simple arduino "synthesizer" I am trying to increment the amount of cycles a melody will be played once a key is pressed (the key in turn passes a value to the variable selectMel). The problem I encounter is that the moment I call my function in the main void loop() function, I cannot control the incrementation of the variable ncycles, which is intended to be only increased once per key press. I tried to solve this by creating a global switchVar variable as an "on/off" switch but that did not do much to solve the issue at hand.    

Any tips or help will be greatly appreciated!

PS: I have of course googled and tried the solutions posted on similar stackExchange posts but to no avail, sadly.

      void playMan (int ncycles, int mSpeed) {

        switch (selectMel) {
        case 1:
          if (ncycles &gt; 0) {
            tone(12, NOTE_B7, mSpeed);
            delay(100);
            tone(12, NOTE_B5, mSpeed);
            delay(100);
            tone(12, NOTE_B3, mSpeed);
            delay(100);
            tone(12, NOTE_B1, mSpeed);
            delay(100);
            ncycles--;
            break;
          case 2:
            if (millis() % 100 == 0) {
              if (switchVar == 1) {
                ncycles += 5;
                switchVar = 0;
              }
              Serial &lt;&lt; ncycles &lt;&lt; endl;
            }
            break;
          default:
            break;
          }
        }
      }
See http://www.gammon.com.au/switches.

Basically you need to detect the transition between the switch not being pressed before, and now being pressed. This transition will occur once per press (possibly after you add debouncing). If you just test for the switch pressed naturally you will get multiple increments.




  Assuming I add debouncing, how would it help in incrementing the value of ncycles only once ?


To clarify, you increment once on a transition, note when you did this (eg, by calling millis() ) and then ignore any further transitions for, say 10 ms.