Bird
0
0
Arduinoprogramming~5 mins

Wire library for I2C in Arduino

Choose your learning style9 modes available
Introduction

The Wire library helps your Arduino talk to other devices using I2C, a simple way to send and receive data between chips.

When you want to connect sensors like temperature or light sensors to your Arduino.
When you need to control small displays that use I2C communication.
When you want to connect multiple devices using only two wires to save pins.
When you want to read data from or send data to another microcontroller.
When you want to build projects that need easy and fast communication between parts.
Syntax
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.

Examples
This starts the Arduino as the master device on the I2C bus.
Arduino
Wire.begin();
// Start I2C as master
This sends a byte (0x00) to the device at address 0x3C.
Arduino
Wire.beginTransmission(0x3C);
Wire.write(0x00);
Wire.endTransmission();
This asks the device at 0x3C for 2 bytes and reads them one by one.
Arduino
Wire.requestFrom(0x3C, 2);
while (Wire.available()) {
  char c = Wire.read();
  // process c
}
Sample Program

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.

Arduino
#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
}
OutputSuccess
Important Notes

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.

Summary

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.