Ticker

6/recent/ticker-posts

Header Ads Widget

Arduino code to find address of connected I2C peripherals

Hello guys, in this code i am using the Wire library for arduino, which is included with the Arduino IDE, to perform an I2C scan. The scan is performed in the loop() function.

The setup() function initializes the serial port and the I2C bus.

In the loop() function, a for loop is used to iterate over all possible I2C addresses (from 1 to 127). For each address, the code sends an I2C "beginTransmission" message to that address using the Wire.beginTransmission() method. If the transmission is successful (i.e. no errors are returned), the code prints a message to the serial monitor indicating that a device has been found at that address. If an error is returned, the code prints a message indicating that an error occurred.

At the end of the scan, the code prints a summary of the results to the serial monitor.

This code can be helpful when working with I2C devices, as it allows you to easily determine the addresses of any devices that are connected to the bus. 



#include <Wire.h>

void setup() {
  Serial.begin(9600);
  Wire.begin();
  while (!Serial); // Wait for serial port to be available
  Serial.println("\nI2C Scanner");
}

void loop() {
  byte error, address;
  int deviceCount = 0;

  Serial.println("Scanning...");
  
  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("  !");
      deviceCount++;
    }
    else if (error==4) {
      Serial.print("Unknown error at address 0x");
      if (address<16) {
        Serial.print("0");
      }
      Serial.println(address,HEX);
    }    
  }

  if (deviceCount == 0) {
    Serial.println("No I2C devices found\n");
  }
  else {
    Serial.println("Done\n");
  }
  delay(5000); // wait 5 seconds for the next scan
}


Post a Comment

0 Comments