The I2C (Inter-Integrated Circuit) module is a serial communication interface that uses two bidirectional lines, SCL (Serial Clock) and SDA (Serial Data), for data transfer. It is widely used in embedded systems to connect microcontrollers to various peripherals like sensors, EEPROMs, RTCs (Real-Time Clocks), and other I2C-enabled devices. The I2C protocol supports multiple masters and slaves on the same bus, making it ideal for complex communication tasks within a system.
Pin Number | Pin Name | Description |
---|---|---|
1 | VCC | Power supply (3.3V or 5V) |
2 | GND | Ground |
3 | SCL | Serial Clock Line |
4 | SDA | Serial Data Line |
5 | ADDR | Address selection pin (if applicable) |
6 | INT | Interrupt output (if applicable) |
#include <Wire.h>
void setup() {
Wire.begin(); // Join the I2C bus as a master or a slave (if an address is specified)
Serial.begin(9600); // Start serial communication for debugging
}
void loop() {
Wire.beginTransmission(0x68); // Begin transmission to a device with address 0x68
// Send data bytes using Wire.write()
Wire.write(0x00); // For example, write to register 0
Wire.endTransmission(); // End transmission and release the I2C bus
delay(1000); // Wait for a second
Wire.requestFrom(0x68, 1); // Request 1 byte from the device at address 0x68
while (Wire.available()) { // Check for received data from the slave
char c = Wire.read(); // Receive a byte
Serial.println(c); // Print the received byte to the serial monitor
}
delay(1000); // Wait for a second
}
Wire
library's onReceive()
and onRequest()
functions to handle I2C communication more effectively.Q: Can I connect multiple devices to the same I2C bus? A: Yes, as long as each device has a unique address and the bus capacitance does not exceed the maximum specified by the standard.
Q: What should I do if two devices have the same I2C address? A: Some devices allow you to change their address using jumpers or additional pins. If that's not possible, you may need to use an I2C multiplexer.
Q: How long can the I2C bus be? A: The maximum length of the I2C bus depends on the bus capacitance and the speed of communication. For standard mode, keep the total bus capacitance under 400 pF.
Q: Can I use I2C with devices that have different voltage levels? A: You will need a level shifter to safely connect devices with different logic levels on the same I2C bus.