I2C Communication Tutorial

I2C Communication between Two Microcontrollers

Difficulty Level: Intermediate

In this tutorial, we will learn how to set up and implement I2C communication between two microcontrollers (e.g., two Arduino boards). The I2C protocol is widely used for communication between microcontrollers and peripheral devices like sensors, displays, and EEPROMs.

Components Required

Understanding I2C

I2C (Inter-Integrated Circuit) is a two-wire communication protocol used in embedded systems to enable multiple devices to communicate over a shared bus. Here’s an overview:

One device is designated as the master, which controls the clock and initiates communication, while other devices act as slaves.

Wiring the Arduinos

Follow the steps below to connect two Arduino boards for I2C communication:

If you experience instability, add 4.7 kΩ pull-up resistors to the SDA and SCL lines.

Arduino Code

Master Arduino Code


#include 

void setup() {
  Wire.begin(); // Initialize I2C as master
  Serial.begin(9600);
}

void loop() {
  Wire.beginTransmission(8); // Address of slave
  Wire.write("Hello Slave!"); // Send message
  Wire.endTransmission();
  delay(1000); // Wait 1 second
}
            

Slave Arduino Code


#include 

void setup() {
  Wire.begin(8); // Initialize I2C with address 8
  Wire.onReceive(receiveEvent); // Set up receive event
  Serial.begin(9600);
}

void receiveEvent(int bytes) {
  while (Wire.available()) {
    char c = Wire.read();
    Serial.print(c);
  }
  Serial.println();
}

void loop() {
  // The slave operates passively
}
            

Upload and Test

  1. Connect the master Arduino to your PC and upload the master code.
  2. Repeat the process for the slave Arduino, uploading the slave code.
  3. Open the serial monitor for the slave Arduino to see the data received from the master.

You should see the message "Hello Slave!" printed on the slave Arduino’s serial monitor every second.

Common Errors

Here are common issues and solutions:

Advanced Applications

Once you’ve mastered basic I2C communication, explore these advanced uses:

Conclusion

In this tutorial, you learned how to set up and implement I2C communication between two Arduino boards. This communication protocol is versatile and can be extended to multiple devices or used with various peripherals.