const int PIN_PG   = 2;  // GPIO 2
const int PIN_RESET = 4; // GPIO 4

String inputCommand = "";

void setup() {
  Serial.begin(115200);
  delay(1000); // give some time for Serial to attach

  pinMode(PIN_PG, OUTPUT);
  digitalWrite(PIN_PG, LOW);

  pinMode(PIN_RESET, INPUT);

  Serial.println("Booting...");
  Serial.println("Ready. Commands: 'pg 1', 'pg 0', 'reset'");
}

void loop() {
  // Heartbeat
  static unsigned long lastBeat = 0;
  if (millis() - lastBeat > 2000) {
    lastBeat = millis();
  }

  while (Serial.available() > 0) {
    char c = Serial.read();

    // Echo back what we received so you can see it
    Serial.write(c);

    // Check for end of line
    if (c == '\n' || c == '\r') {
      if (inputCommand.length() > 0) {
        Serial.print("\nReceived command: [");
        Serial.print(inputCommand);
        Serial.println("]");

        handleCommand(inputCommand);
        inputCommand = "";
      }
    } else {
      inputCommand += c;
    }
  }
}

void handleCommand(String cmd) {
  cmd.trim();  // remove spaces/newlines

  if (cmd == "pg 1") {
    pinMode(PIN_PG, OUTPUT);
    digitalWrite(PIN_PG, HIGH);
    Serial.println("PG -> HIGH");

  } else if (cmd == "pg 0") {
    pinMode(PIN_PG, OUTPUT);
    digitalWrite(PIN_PG, LOW);
    Serial.println("PG -> LOW");

  } else if (cmd == "reset") {
    Serial.println("Reset sequence on GPIO 4");
    pinMode(PIN_RESET, OUTPUT);
    digitalWrite(PIN_RESET, LOW);
    delay(500); // 0.5 sec
    pinMode(PIN_RESET, INPUT);
    Serial.println("GPIO 4 back to INPUT");

  } else {
    Serial.print("Unknown command: ");
    Serial.println(cmd);
  }
}
