Editorial Solution

From the task, we understand that,

  • The Arduino Uno acts as an I2C master(scanner).
  • The master will scan all possible 7-bit I2C addresses (0x01 to 0x7F).
  • If a slave responds to an address, the master will display the address on the Serial Monitor.
  • Also prints the total number of slaves connected.

Hardware Connection for an I2C Address Scanner

  • All I2C slave devices are connected in parallel, sharing the same SDA and SCL lines with Master(Arduino UNO).
  • Ensure each device has unique I2C addresses to avoid conflicts.
  • Connect the VCC and GND of each device to the corresponding pins on the master.
  • Pull-up Resistors:
    • Add pull-up resistors (typically 4.7 kΩ) on the SDA and SCL lines.
    • Connect one pull-up resistor between SDA and VCC, and another between SCL and VCC.

Circuit Connection

Firmware

Code(I2C Scanner)

#include <Wire.h>

void setup() {
  Wire.begin();                // Initialize I2C
  Serial.begin(115200);          // Initialize Serial communication
  Serial.println("\nI2C Scanner");
}

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

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

  for (address = 1; address <= 127; address++) { // I2C addresses range from 1 to 127
    Wire.beginTransmission(address);
    error = Wire.endTransmission();

    if (error == 0) { // Device responded
      Serial.print("I2C device found at address 0x");
      if (address < 16) Serial.print("0");
      Serial.println(address, HEX);
      devices++;
    } else if (error == 4) {
      Serial.print("Unknown error at address 0x");
      if (address < 16) Serial.print("0");
      Serial.println(address, HEX);
    }
  }

  if (devices == 0) {
    Serial.println("No I2C devices found\n");
  } else {
    Serial.print("Total no. of slave devices connected are ");
    Serial.println(devices);
    Serial.println("Scan complete\n");
  }

  delay(5000); // Wait 5 seconds before scanning again
}

 

Code Explanation

  1. I2C Master Mode
    • The Arduino Uno is set to act as an I2C master using the Wire.begin() function.
  2. Address Scanning
    • The code loops through all possible 7-bit I2C addresses (0x01 to 0x7F) and checks for acknowledgment using Wire.beginTransmission() and Wire.endTransmission().
  3. Error Handling
    • If Wire.endTransmission() returns 0, which means the slave responded successfully.
    • If it returns other error codes (e.g., 4), the error is logged to the Serial Monitor.
  4. Serial Output
    • The detected I2C slave addresses are displayed in hexadecimal format and total number of slave devices on the Serial Monitor.

Output

Sample output with one slave device connected 

 

Sample output with two slave devices connected 

Submit Your Solution