From the task, we understand that,
#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
}
Wire.begin()
function.Wire.beginTransmission()
and Wire.endTransmission()
.Wire.endTransmission()
returns 0, which means the slave responded successfully.Sample output with one slave device connected
Sample output with two slave devices connected