#include <Wire.h>

#define IIC_SDA 10
#define IIC_SCL 8
#define IIC_Freq 100000

void setup() {
  Wire.begin(IIC_SDA, IIC_SCL, IIC_Freq); // 初始化 I2C 总线
  Serial.begin(115200); // 初始化串口通信
  Serial.println("\nI2C Scanner");
}

void loop() {
  byte error, address;
  int nDevices;

  Serial.println("Scanning...");

  nDevices = 0;
  for (address = 1; address < 127; address++) { // 遍历所有可能的 I2C 地址
    Wire.beginTransmission(address);
    error = Wire.endTransmission();

    if (error == 0) { // 如果没有错误，表示找到设备
      Serial.print("I2C device found at address 0x");
      if (address < 16) Serial.print("0");
      Serial.println(address, HEX); // 打印设备地址
      nDevices++;
    } else if (error == 4) { // 未知错误
      Serial.print("Unknown error at address 0x");
      if (address < 16) Serial.print("0");
      Serial.println(address, HEX);
    }
  }

  if (nDevices == 0) {
    Serial.println("No I2C devices found");
  } else {
    Serial.println("done");
  }

  delay(5000); // 等待 5 秒后再次扫描
}