#include <Wire.h>

/*
   scanner for devices on i2c bus
*/


//JDN testet dor uno,mega, esp32 nodemcu
void setup()
{
  Wire.begin();

  Serial.begin(115200);
  while (!Serial);             // Leonardo: wait for serial monitor
  Serial.println("\nI2C Scanner");
}

void testSlave(byte address)
{
  byte resp[10];


  switch (address) {
    case 0x68:  // mpu6050
    case 0x69:
      Wire.beginTransmission(address);
      Wire.write(byte(0x75));  // get id register on addr 0x75
      Wire.endTransmission();
      Wire.requestFrom(address, 1);
      resp[0] = Wire.read();
      Serial.print(" id: 0x"); Serial.print(resp[0], HEX); Serial.print(" (IMU mpu6050: 0x68)");
      break;
    case 0x76:  // bmp280
    case 0x77:  // bmp
      Wire.beginTransmission(address);
      Wire.write(byte(0xd0));  // get id registe on addr 0xd0 s
      Wire.endTransmission();
      Wire.requestFrom(address, 1);
      resp[0] = Wire.read();
      Serial.print(" id: 0x"); Serial.print(resp[0], HEX); Serial.print(" ("); Serial.print("bmp085: 0x55, bmp180: 0x55, bmp280: 0x58)");
      break;
    case 0x1e:  // hmc5983 
      Wire.beginTransmission(address);
      Wire.write(byte(0x0a));  // get id registe on addr 0x75
      Wire.endTransmission();
      Wire.requestFrom(address, 3);
      resp[0] = Wire.read();
      resp[1] = Wire.read();
      resp[2] = Wire.read();
      Serial.print(" id: 0x"); Serial.print(resp[0], HEX); Serial.print(" ");
      Serial.print("0x"); Serial.print(resp[1], HEX); Serial.print(" ");
      Serial.print("0x"); Serial.print(resp[2], HEX); Serial.print(" ");
      
      
      Serial.print(" (HMC: 5983 0x48 0x34, 0x33)");
      break;
      
      
    default :;
  }

}

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

  Serial.println("\n\n\n\nScanning...");

  nDevices = 0;
  for (address = 1; address < 127; address++ )
  {
    // The i2c_scanner uses the return value of
    // the Write.endTransmisstion to see if
    // a device did acknowledge to the address.
    Wire.beginTransmission(address);
    error = Wire.endTransmission();

    if (error == 0)
    {
      Serial.print("I2C device: 0x");
      if (address < 16)
        Serial.print("0");
      Serial.print(address, HEX);
      Serial.print("  (");
      Serial.print(address);
      Serial.print(") ");
      testSlave(address);
      Serial.println("");

      nDevices++;
    }
    else if (error == 4)
    {
      Serial.print("Unknow error at address 0x");
      if (address < 16)
        Serial.print("0");
      Serial.println(address, HEX);
    }
  }

  if (nDevices == 0)
    Serial.println("No I2C devices found\n");
  else {
    Serial.print("found: "); Serial.print(nDevices); Serial.println(" devices");
  }
  delay(1000);           // wait 5 seconds for next scan
}
