0

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 > 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 << ncycles << endl;
            }
            break;
          default:
            break;
          }
        }
      }

1 Answer 1

2

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.

2
  • Assuming I add debouncing, how would it help in incrementing the value of ncycles only once ? From what I understand debouncing is only helpful as a means of toggling from one state to another without the "noise" of outside factors, or is there something I am missing entirely?
    – gnzg
    Jan 12, 2016 at 21:23
  • I have just found a solution to my own question, albeit not without your kind help Mr. Gammon, thank you!
    – gnzg
    Jan 12, 2016 at 22:11

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.