 }
 
 void loop() {
+  if (Serial.available() > 0) {
+    byte incomingByte = Serial.read();
+    if (incomingByte == '\n') {
+      if (serial_unfinished_line == "PING;") {
+        Serial.println("PONG;");
+      } else if (serial_unfinished_line.startsWith("PONG,")) {
+        String tmp = serial_unfinished_line.substring(5,6);
+        if (tmp == "0") {
+          if (state == UNLOCKED) {
+            setState(LOCKED);
+          }
+        } else if (tmp == "1") {
+          if (state != UNLOCKED) {
+            setState(UNLOCKED);
+          }
+        }
+      } else {
+        serial_buffer = serial_unfinished_line;
+      }
+      serial_unfinished_line = "";
+    } else {
+      serial_unfinished_line += (char)incomingByte;
+    }
+  }
+    
   if (state == LOCKED) {
     // Look for new cards
     if ( ! mfrc522.PICC_IsNewCardPresent()) {

    if (key) {
      if (key == '#' || key == '*') {
        if (buffer == "0") {
          Serial.print("LOCK;");
          setState(LOCKED);
        }        
      } else {

long timeout_start = 0;
long timeout = 10000;

String serial_buffer = "";
String serial_unfinished_line = "";
String buffer = "";

void updateDisplay() {
  lcd.clear();
  if (state == LOCKED) {
    lcd.print("Hello Stranger! ");
    lcd.setCursor(0, 1);
    lcd.print(" Door is locked.");
  } else if (state == PIN_ENTRY) {
    lcd.print("Please enter PIN");
    lcd.setCursor(0, 1);
    for (int i = 0; i < buffer.length(); i++) {
      lcd.print("*");
    }
  } else if (state == WAIT_FOR_UNLOCK) {
    lcd.print("Waiting for     ");
    lcd.setCursor(0, 1);
    lcd.print("   confirmation ");
  } else if (state == INVALID_PIN) {
    lcd.print("Invalid PIN     ");
    lcd.setCursor(0, 1);
    lcd.print("Please try again");
  } else if (state == UNLOCKED) {
    lcd.print("Space is open   ");
    lcd.setCursor(0, 1);
    lcd.print("Press 0# to lock");
