Connecting multiple I2C devices lets you use many sensors or modules with just two wires. This saves space and wiring complexity.
Connecting multiple I2C devices in Arduino
Wire.begin();
// For each device, use its unique I2C address
Wire.beginTransmission(device_address);
// Send or request data
Wire.endTransmission();Each I2C device must have a unique address to avoid conflicts.
Use Wire.begin() once in setup() to start I2C communication.
Wire.begin(); Wire.beginTransmission(0x40); // Device 1 address // communicate with device 1 Wire.endTransmission(); Wire.beginTransmission(0x41); // Device 2 address // communicate with device 2 Wire.endTransmission();
Wire.begin(); // Read from device 1 Wire.requestFrom(0x40, 2); while (Wire.available()) { char c = Wire.read(); // process data } // Read from device 2 Wire.requestFrom(0x41, 2); while (Wire.available()) { char c = Wire.read(); // process data }
This program shows how to talk to two I2C devices with addresses 0x40 and 0x41. It sends a command and reads one byte from each device, then prints the data to the Serial Monitor.
#include <Wire.h> void setup() { Serial.begin(9600); Wire.begin(); Serial.println("Starting I2C communication with two devices..."); } void loop() { // Communicate with device at address 0x40 Wire.beginTransmission(0x40); Wire.write(0x00); // example command Wire.endTransmission(); Wire.requestFrom(0x40, 1); if (Wire.available()) { int data1 = Wire.read(); Serial.print("Data from device 0x40: "); Serial.println(data1); } // Communicate with device at address 0x41 Wire.beginTransmission(0x41); Wire.write(0x00); // example command Wire.endTransmission(); Wire.requestFrom(0x41, 1); if (Wire.available()) { int data2 = Wire.read(); Serial.print("Data from device 0x41: "); Serial.println(data2); } delay(2000); // wait 2 seconds before next read }
Make sure each device has a unique I2C address; some devices allow changing their address with pins.
Use pull-up resistors (usually 4.7kΩ) on SDA and SCL lines if your board or devices don't have them built-in.
Check device datasheets for their I2C addresses and commands.
Multiple I2C devices share the same two wires but must have unique addresses.
Use Wire.begin() once, then communicate with each device by its address.
Pull-up resistors and correct wiring are important for reliable communication.
