title: How to execute code once only when an RFID card is present or not
body: <p>My code is super simple, but I'm at a loss how to do a simple task.</p>
  
  <p>Each time an RFID card is read, I want it to trigger an event once. This is working fine in isolation.</p>
  
  <p>However, I also want a different one-time event to occur each time a card is taken away. This bit seems to mess up the whole thing.</p>
  
  <p>I'm using the MFRC522 Library. </p>
  
  <p>Could anyone tell me the method to do both within the same code? I'm kind of green as to all this.</p>
  
  <p>Many thanks in advance :) My code is here:</p>
  
  <pre><code>#include &lt;MFRC522.h&gt; 
  #define SS_PIN 10
  #define RST_PIN 9
  MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.
  
  bool executed = false;
  
  
  void setup() {
    Serial.begin(9600);   // Initiate a serial communication    
    SPI.begin();      // Initiate  SPI bus
    mfrc522.PCD_Init();   // Initiate MFRC522
  }
  
  
  void loop() { 
  
    if ( mfrc522.PICC_IsNewCardPresent()) {    
      if ( mfrc522.PICC_ReadCardSerial()) {
        Serial.println("Great!.. each time a card is read and re-read this text will print *ONCE ONLY*");
      }     
    } 
  
  // BELOW I WANT TO EXECUTE A COMMAND *ONCE ONLY* EACH TIME A CARD IS TAKEN AWAY
  // WHEN UNCOMMENTED, THE "Oh dear.." PRINTS CONTINUOUSLY 
  
  //  if ( !mfrc522.PICC_IsNewCardPresent()) {  
  //    Serial.println("Oh dear... this seems to keep printing... ");  
  //  }
  
    mfrc522.PICC_HaltA();          // Halt PICC
    mfrc522.PCD_StopCrypto1();     // Stop encryption on PCD  
  }
  </code></pre>
  
  <p>Also, the revised code that I also tried is as follows. This also did not work. It printed the card present fine but when the card was taken away multiple prints continuously occured:</p>
  
  <pre><code>    #include &lt;SPI.h&gt;
  #include &lt;MFRC522.h&gt;
  #define RST_PIN    9
  #define SS_PIN    10
  
  MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance
  
  bool executed = false;
  
  void setup() {
    Serial.begin(9600); // Initialize serial communications with the PC
    SPI.begin(); // Init SPI bus
    mfrc522.PCD_Init(); // Init MFRC522
    Serial.println("Waiting for RFID-chip...");
  }
  
  void loop() {
    if ( mfrc522.PICC_IsNewCardPresent()) {    
      if ( mfrc522.PICC_ReadCardSerial()) {
        Serial.println("Great!.. each time a card is read and re-read this text will print *ONCE ONLY*");
        executed = true;
      }     
    } 
    else {  
      if (executed) {
        Serial.println("Oh dear... this seems to keep printing... ");  
        executed = false;
      }
    }
  }
  </code></pre>