Nov 21, 2016

Scan for I2C Devices on Bus [arduino function]

Update in 2018:
Here's a much shorter version of this as a function call (no args, no return value). Maintained on github here.


void i2cScan() {
    Serial.println ("\ni2cScan...\n");
    static int count = 0;

    Wire.begin();
    for (int i = 8; i < 120; i++)
    {
        Wire.beginTransmission(i);          // probe this i2c address
        if (Wire.endTransmission() == 0)
        {
            Serial.print ("  device at: 0x" + String(i, HEX) + "  [" + String(i) + "] \n");            count++;
            delay (1);
        }
    }
    Serial.print("\nTotal devices:  " + String(count) + "\n");
}


Updated a diagnostic script to be a function with optional outputs [Arduino]

n = i2cScan(0);   // prints nothing; returns 0|1 for successful read of at least one device

n = i2cScan(1);  // prints address of successfully read devices (arg of 2 prints result of every address)

output:
I2C device at 0x19     25
I2C device at 0x1E     30
I2C device at 0x3C     60
I2C device at 0x40     64
I2C device at 0x6B     107
I2C device at 0x77     119
6 devices found.



code:


// --------------------------------------------------
int i2cScan(int printFlag) {
  int nDevices = 0;
  int error = 0;

  for (int 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) {
      if (printFlag > 0) {
        Serial.print("I2C device at 0x");
        if (address < 0x10) Serial.print("0");  // leading zero
        Serial.print(address, HEX);
        Serial.print("\t "); Serial.println(address); // dec
      }
      nDevices++;
    }
    else if (error > 0 && error != 99) {     // 2 = no device
      if (printFlag == 2) {
        Serial.print("   Error:"); Serial.print(error); Serial.print(" at 0x");
        if (address < 0x10) Serial.print("0");   // leading zero
        Serial.print(address, HEX);
        Serial.print("\t "); Serial.println(address); // dec
      }
    }
  }
  if (nDevices == 0) {
    if (printFlag > 0)  Serial.println("No devices found.\n");
  }
  else {
    if (printFlag > 0) {
      Serial.print(nDevices); Serial.println(" devices found.\n");
    }
  }
  return (nDevices == 0); // 0 for no errors and at least one device;
}


More info about i2c at http://www.gammon.com.au/i2c

No comments: