Problem with an alarm, tone and a while loop

Hello everyone, i have this piece of alarm code that turns on when my reedSwitch doesn't has the magnet near.

It works well, if alarm is activated, and the magnet is not near the reed Switch it starts the while. the while is activated and blinking lights until you press the button one of my IR controller.

The problem comes when I insert the bold line of code ("tone"), now it sounds and it keeps blinking the LEDs, but I Cannot exit from it...

Could you please help me? It is getting frustrating

Thank you very much :slight_smile:

void fsalarma1 (){
  
  val1=digitalRead(SWITCH1);

  


  if (alarma1 && val1 == LOW){
    
     Serial.println("Alarma UNO sonando");   
     
     while(alarma1){
       
         
      [b] digitalWrite(altavoz, 100);
       tone(8, 200, 50);
       delay(50);
       noTone(8);[/b]
       
       unsigned long ircode;
       ircode = ir.read();
        
             if(ircode == but1){
               alarma1 = !alarma1;
                estadoverde1 = alarma1;
                digitalWrite(ledverde1, estadoverde1);
                noTone(8);
               Serial.println("apagada1");
               }
        
        
                
        
        digitalWrite(ledazul,100);
        digitalWrite(ledverde1, 100);
        delay (50);
        digitalWrite(ledazul,0);
        digitalWrite(ledverde1, 0);
        digitalWrite(ledrojo,100);
        delay (50);
        digitalWrite(ledrojo,0);
      }  
   }
   
    

}
val1=digitalRead(SWITCH1);

How is the SWITCH1 wired up?
Preferred method is to use an input pin with pullup resister enabled
pinMode(SWITCH1, INPUT_PULLUP);
and then have the switch connect the pin to Gnd when pressed.
Then test for val1 being LOW.

if ( alarma1 && (val1 == LOW) ){

If the code enters the while loop, the only for it to exit the loop is if alarma1 is set to zero. This happens only if "ircode == but1". You will have to figure out why ircode never equals but1.

It would help if you used the IDE menu Tools|Auto Format on your code before posting it. Also get rid of most of the blank lines.

Pete