This Arduino code scans the I2C bus for connected devices and prints their addresses. What will it print if two devices with addresses 0x3C and 0x68 are connected?
void setup() {
Wire.begin();
Serial.begin(9600);
while (!Serial);
Serial.println("Scanning I2C devices...");
for (byte address = 1; address < 127; address++) {
Wire.beginTransmission(address);
byte error = Wire.endTransmission();
if (error == 0) {
Serial.print("Device found at 0x");
if (address < 16) Serial.print("0");
Serial.println(address, HEX);
}
}
Serial.println("Scan complete.");
}
void loop() {}Think about how the code checks all addresses from 1 to 126 and prints each device found.
The code scans all possible I2C addresses and prints each device found. Since devices at 0x3C and 0x68 respond, both addresses are printed.
When connecting multiple I2C devices to the same bus, why must each device have a unique address?
Think about how the master identifies devices on the bus.
Each I2C device must have a unique address so the master can select and communicate with the correct device without confusion or data collision.
The code below is intended to scan for two I2C devices at addresses 0x20 and 0x21. However, it only properly detects the device at 0x20. What is the problem?
void setup() {
Wire.begin();
Serial.begin(9600);
Serial.println("Scanning I2C devices...");
Wire.beginTransmission(0x20);
if (Wire.endTransmission() == 0) {
Serial.println("Device found at 0x20");
}
Wire.beginTransmission(0x21);
Wire.endTransmission();
Serial.println("Device found at 0x21");
}
void loop() {}Look carefully at how the code checks for the device at 0x21.
The code calls Wire.endTransmission() for 0x21 but does not check its return value. It prints the device found message unconditionally, so it always prints that 0x21 is found even if it is not.
Choose the code snippet that correctly initializes two I2C devices with addresses 0x40 and 0x41 using the Wire library.
Remember that Wire.begin() initializes the master and beginTransmission starts communication with a device.
Wire.begin() initializes the I2C master. To communicate with devices, beginTransmission and endTransmission are used with each device's address. Options B and C misuse begin(), and A uses requestFrom which reads data but does not initialize devices.
You have two I2C sensors that both use the fixed address 0x50 and cannot be changed. How can you connect and use both sensors on the same Arduino I2C bus?
Think about hardware solutions to address conflicts on the I2C bus.
When two devices have the same fixed address, an I2C multiplexer can isolate one device at a time, allowing the master to communicate without address conflicts. The Arduino cannot change device addresses or handle conflicts automatically.
