Monday, May 11, 2015

i2c Scanner

I wanted to share a useful script that I have written to determine the available addresses on Arduino's i2c (pronounced "eye-squared-see") bus.  When attaching new hardware where you may not have the address for the device available, this script can be useful to determine that information.  It is also useful for debugging connectivity issues on an i2c bus.

To use, connect your hardware to the bus clock and data lines.  Apply power and ground your hardware as well.  Run this script and open the serial monitor at 115200 baud.  You can change this speed to suit your preferences.  The serial monitor window will list all of the device addresses found on the bus.

As always, if you need assistance, please let me know by dropping me a note at ko7m at arrl dot net or by posting here and I will try to help you out.

// i2c_scanner
//

#include <Wire.h>

void setup()
{
  Wire.begin();

  Serial.begin(115200);
  Serial.println("i2c Scanner");
}

void printAddress(byte address)
{
  if (address<16) Serial.print("0");
  Serial.println(address, HEX);
}

void loop()
{
  

    Serial.println("Scanning...");
  
    int nDevices = 0;
    
    for(int address = 1; address < 127; address++ ) 
    {
      Wire.beginTransmission(address);
      int error = Wire.endTransmission();
      
      // Just for good measure, try again
      if (error != 0)
      {
//        Serial.print("Error ");
//        Serial.println(error, DEC);
//        Serial.println("Retrying...");
        delay(10);
        Wire.beginTransmission(address);
        error = Wire.endTransmission();
      }
  
      if (error == 0)
      {
        Serial.print("i2c device found at address 0x");
        printAddress(address);  
        nDevices++;
      }
      else if (error == 4) 
      {
        Serial.print("Unknown error at address 0x");
        printAddress(address);
      }    
    }
    if (nDevices == 0)
      Serial.println("No i2c devices found\n");
    else
      Serial.println("");

  // Hang the script
  while (1==1);
}

No comments:

Post a Comment