Categories

Follow

I2C Scanner

This is a basic example which will display via the serial monitor the address of any devices connected to your Wemos.

Its the same as one used on Arduino’s.

Code

#include <Wire.h>
 
 
void setup()
{
  Wire.begin();
 
  Serial.begin(9600);
  Serial.println("\nI2C Scanner");
}
 
 
void loop()
{
  byte error, address;
  int nDevices;
 
  Serial.println("Scanning...");
 
  nDevices = 0;
  for(address = 1; address < 127; address++ ) 
  {
 
    Wire.beginTransmission(address);
    error = Wire.endTransmission();
 
    if (error == 0)
    {
      Serial.print("I2C device found at address 0x");
      if (address<16) 
        Serial.print("0");
      Serial.print(address,HEX);
      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.println("done\n");
 
  delay(5000);           // wait 5 seconds for next scan
}

3 comments to I2C Scanner

  • stam

    For some reason, if I want it to work on my ESP8266 ESP-01 I have to replace

    Wire.begin();
    With:
    Wire.begin(0,2);

    Hope it helps someone 😉

    • shedboy71

      Wire.begin() assumes SDA and SCL are certain pins, but you can set them to any other pin by calling Wire.begin([SDA], [SCL]). Which is what you have done.

  • Robert

    Good Job.
    You safed me from using my oscilloscope and starting to find an hardware bug where no bug is 🙂

    Thanks

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

  

  

  

*