Magnetic switch loop

tcjwm:

MarkT:
The whole point is that to detect a state change on a pin you must
remember the previous state on the pin to compare with the current state.

Thanks MarkT.
I tried your code with my magnet and it works.
but how to make the action perform one time only when the state doesn't change? Let say when the box open, it only play the action one time only, and when it close, it do nth.

int buttonPin = 2; 

void setup ()
{
  Serial.begin(9600);
  pinMode (buttonPin, INPUT);
}

int now_state = 0;
int pre_state = 7;
int box=0;
void loop()
{
   now_state = digitalRead(buttonPin);
   if (now_state != pre_state)
  {
   if(now_state == LOW)
     {
      // A transition occurred...
         Serial.print('1');
         delay(1000);
         Serial.print('0');
         delay(1000);
         Serial.println("hey how are you");
       
     }
     pre_state = now_state;
  }
}

This code that you posted that I quoted above will do just what you requested (difficult to tell because your indenting is a bit off, use CTRL-T in the IDE to clean that up) but instead of playing music it will print to the serial monitor just once when the digital signal at pin 2 goes low. (Did you actually try it out and see the effect?)

I just took a look at the code in your first posting (kindly go back and edit that post to add the code tags...) and I see a bunch of commands being sent out to another device via SPI where it looks like you want music to be played. You have not given us any description of what is on the receiving end of those commands (a link to a datasheet would be nice as well) that I presume is doing the job of playing the music. It might be as simple as sending a different command (one that means play once instead of one that means play repeatedly), or you need to know when to send an additional command to tell it to stop. Either after the appropriate amount of time, or when the lid closes (this is simple to add sending the command over SPI as an else clause to the inner nested if statement), or both.