Trying to find a better way to trigger

During this segment I want to play the tone on repeat indefinitely with a slight pause between rings until the user presses the button. What I currently have works but has very small detection window where if you don't hold down the button it will miss it. How can I have it detect the button press without it being held in order to break from the loop. Thanks for any help!

    case MODE_RINGING:
    
    if (dButtonPressed == false) {
     for  (int thisNote = 0; thisNote < 10; thisNote++) {
     int noteDuration = 1000 / noteDurations[thisNote];
     tone(4, melody[thisNote], noteDuration);
     int pauseBetweenNotes = noteDuration * 1.30;
     delay(pauseBetweenNotes);
     noTone(4);  }
     delay(4000);  
      break;
  
    }
    else { break; }
     
  }

How can I have it detect the button press without it being held in order to break from the loop.

in loop(), detect when it becomes pressed and set a flag. Test the flag in the MODE_RINGING state and act on it as appropriate

Here is a tutorial on how to determine when a button BECOMES pressed rather than IS pressed.

StateChangeDetection

Also, since no matter whether the button is pressed or not you need the 'break' statement and therefore you can remove the 'else':

case MODE_RINGING:
  if (dButtonPressed == false) {
    for  (int thisNote = 0; thisNote < 10; thisNote++) {
      int noteDuration = 1000 / noteDurations[thisNote];
      tone(4, melody[thisNote], noteDuration);
      int pauseBetweenNotes = noteDuration * 1.30;
      delay(pauseBetweenNotes);
      noTone(4);
    }
    delay(4000);
  }
  break;

Loose delay(). You have to change your thinking away from "following a trail".

-jim lee

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.