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;
}
}