Advertisement
Tywais

I2C Scanner

Jul 19th, 2025 (edited)
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.72 KB | None | 0 0
  1. /* ---------------------------------------------------------------- /
  2.     // Arduino I2C Scanner
  3.     // Re-writed by Arbi Abdul Jabbaar
  4.     // Using Arduino IDE 1.8.7
  5.     // Using GY-87 module for the target
  6.     // Tested on 10 September 2019
  7.     // This sketch tests the standard 7-bit addresses
  8.     // Devices with higher bit address might not be seen properly.
  9.     / ---------------------------------------------------------------- /
  10. */   
  11.     #include <Wire.h> //include Wire.h library
  12.      
  13.     void setup()
  14.     {
  15.       Wire.begin(22,21); // Wire communication begin
  16.       Serial.begin(115200); // The baudrate of Serial monitor is set in 9600
  17.       while (!Serial); // Waiting for Serial Monitor
  18.       Serial.println("\nI2C Scanner");
  19.     }
  20.      
  21.     void loop()
  22.     {
  23.       byte error, address; //variable for error and I2C address
  24.       int nDevices;
  25.      
  26.       Serial.println("Scanning...");
  27.      
  28.       nDevices = 0;
  29.       for (address = 1; address < 127; address++ )
  30.       {
  31.         // The i2c_scanner uses the return value of
  32.         // the Write.endTransmisstion to see if
  33.         // a device did acknowledge to the address.
  34.         Wire.beginTransmission(address);
  35.         error = Wire.endTransmission();
  36.      
  37.         if (error == 0)
  38.         {
  39.           Serial.print("I2C device found at address 0x");
  40.           if (address < 16)
  41.             Serial.print("0");
  42.           Serial.print(address, HEX);
  43.           Serial.println("  !");
  44.           nDevices++;
  45.         }
  46.         else if (error == 4)
  47.         {
  48.           Serial.print("Unknown error at address 0x");
  49.           if (address < 16)
  50.             Serial.print("0");
  51.           Serial.println(address, HEX);
  52.         }
  53.       }
  54.       if (nDevices == 0)
  55.         Serial.println("No I2C devices found\n");
  56.       else
  57.         Serial.println("done\n");
  58.      
  59.       delay(5000); // wait 5 seconds for the next I2C scan
  60.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement