#include <Wire.h>
#include "Adafruit_SGP30.h"

Adafruit_SGP30 sgp;

void scanI2C() {
  Serial.println("I2C scan start...");
  byte count = 0;
  for (byte addr = 1; addr < 127; addr++) {
    Wire.beginTransmission(addr);
    if (Wire.endTransmission() == 0) {
      Serial.print("Found I2C device: 0x");
      if (addr < 16) Serial.print("0");
      Serial.println(addr, HEX);
      count++;
      delay(2);
    }
  }
  if (count == 0) Serial.println("No I2C device found.");
  Serial.println("SGP30 should be 0x58.");
}

void setup() {
  Serial.begin(115200);
  while (!Serial) delay(10);

  // UNO/Nano: SDA=A4, SCL=A5. ESP32 可改为 Wire.begin(21, 22);
  Wire.begin();
  Wire.setClock(100000);

  scanI2C();

  if (!sgp.begin()) {
    Serial.println("SGP30 not found. Check VCC/GND/SDA/SCL and I2C address 0x58.");
    while (1) delay(1000);
  }

  Serial.println("SGP30 found.");
  Serial.print("Serial #");
  Serial.print(sgp.serialnumber[0], HEX);
  Serial.print(sgp.serialnumber[1], HEX);
  Serial.println(sgp.serialnumber[2], HEX);
}

void loop() {
  if (!sgp.IAQmeasure()) {
    Serial.println("Measurement failed");
    delay(1000);
    return;
  }

  Serial.print("TVOC ");
  Serial.print(sgp.TVOC);
  Serial.print(" ppb\t");
  Serial.print("eCO2 ");
  Serial.print(sgp.eCO2);
  Serial.println(" ppm");

  delay(1000);
}
