The Wire library helps your Arduino talk to other devices using I2C, a simple way to send and receive data between chips.
Wire library for I2C in Arduino
Wire.begin();
Wire.beginTransmission(address);
Wire.write(data);
Wire.endTransmission();
Wire.requestFrom(address, quantity);
while (Wire.available()) {
byte c = Wire.read();
}Wire.begin() starts the I2C bus on your Arduino.
address is the 7-bit I2C address of the device you want to talk to.
Wire.begin();
// Start I2C as masterWire.beginTransmission(0x3C); Wire.write(0x00); Wire.endTransmission();
Wire.requestFrom(0x3C, 2); while (Wire.available()) { char c = Wire.read(); // process c }
This program starts I2C, sends a byte to a device at address 0x3C, then reads one byte back and prints it to the Serial Monitor every second.
#include <Wire.h> void setup() { Serial.begin(9600); Wire.begin(); // Start I2C as master } void loop() { Wire.beginTransmission(0x3C); // Device address Wire.write(0x00); // Send a command or data Wire.endTransmission(); Wire.requestFrom(0x3C, 1); // Request 1 byte if (Wire.available()) { byte data = Wire.read(); Serial.print("Received: "); Serial.println(data); } delay(1000); // Wait 1 second }
Always check the device's 7-bit I2C address before communicating.
Use pull-up resistors on the SDA and SCL lines if your board or device does not have them built-in.
Wire library uses 7-bit addresses; some datasheets show 8-bit addresses, so be careful.
The Wire library makes I2C communication easy on Arduino.
Use Wire.begin() to start, Wire.beginTransmission() and Wire.endTransmission() to send data, and Wire.requestFrom() to receive data.
I2C uses only two wires to connect many devices, saving pins and simplifying wiring.
