Saturday, March 28, 2020

I2C Scanner

Since always when I am working with I2C devices I need the scanner I will post here for me and for others:

#include <Wire.h>


void setup()
{
  Wire.begin();

  Serial.begin(115200);
  Serial.println(F("\nI2C Scanner"));

  byte error, address;
  int nDevices;

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

  nDevices = 0;
  for(address = 1; address < 127; address++ )
  {

    Wire.beginTransmission(address);
    error = Wire.endTransmission();

    if (error == 0)
    {
      Serial.print(F("I2C device found at address 0x"));
      if (address<16)
        Serial.print("0");
      Serial.print(address,HEX);
      Serial.println(F("  !"));

      nDevices++;
    }
    else if (error==4)
    {
      Serial.print(F("Unknow error at address 0x"));
      if (address<16)
        Serial.print(F("0"));
      Serial.println(address,HEX);
    } 
  }
  if (nDevices == 0)
    Serial.println(F("No I2C devices found\n"));
  else
    Serial.println(F("done\n"));

}


void loop()
{}