Open Sayeed97 opened 3 months ago
Summary:
I2C protocol involves using two lines to send and receive data
Serial Data Line (SDL) - Used to transfer the actual data Serial Clock Line (SCL) - Used to provide the clock pulses for data interpretation
There is one controller device connected to one or more peripheral devices connected through SDL and SCL
Working:
Each device in the I2C bus is functional and independent from the controller but will respond with information when prompted by the controller. Each device has its unique address, and the controller and peripheral take turns to communicate with each other.
Message Sequence: {Start Bit} -> {Device ID (7 bit)} -> {Read/Write} -> {Acknowledge Bit} -> {8 Bit Data} -> {Acknowledge Bit} -> {...} -> {Stop Bit}
Note: Since the Device ID or Address is 7 bit the total number of possible devices for I2C we can have is 0-127.
Arduino test code for scanning I2C device address range
Wire API reference: https://www.arduino.cc/reference/en/language/functions/communication/wire/
Note: You can find the device I2C address from the data sheet
// I2C address finding
#include <Wire.h>
void setup()
{
//Initializing wire
Wire.begin();
//Initializing seraial monitor at the baudrate of 9600
Serial.begin(9600);
}
void loop()
{
byte err, addr;
//Declaring variable to detect and count no. of I2C device found
int devices = 0;
// For loop to try multiple combinations of Address
for (addr = 1; addr < 127; addr++)
{
Wire.beginTransmission(addr);
err = Wire.endTransmission();
// err = 0 for a successful transmission end
// !0 == true; which means we have a successfully found a device in the provided address
if (!err)
{
Serial.print("Device address: 0x");
Serial.println(addr, HEX);
devices++;
}
else if (err == 4) // unknown error from the I2C device
{
Serial.print("Error at address: 0x");
Serial.println(addr, HEX);
}
}
//Exception, when there is no I2C device found
if (!devices)
{
Serial.println("Please connect your I2C device");
}
//Waiting for 2 seconds
delay(2000);
}
Wire.h library allows you to communicate with I2C devices, a feature that is present on all Arduino boards. I2C is a very common protocol, primarly used for reading/sending data to/from external I2C components.
References: