What is I2C Protocol in Embedded C: Simple Explanation and Example
I2C protocol is a communication method used in embedded systems to connect multiple devices using just two wires: one for data (SDA) and one for clock (SCL). In Embedded C, it allows microcontrollers to send and receive data with sensors or other chips efficiently over this shared bus.How It Works
Imagine a group of friends passing notes in class using just two strings: one to send the note (data) and one to keep the timing (clock). The I2C protocol works similarly by using two wires called SDA (data line) and SCL (clock line) to let multiple devices talk to each other.
One device acts as the master controlling the clock and starting communication, while others are slaves that listen and respond. Each device has a unique address, so the master can pick who to talk to. Data is sent bit by bit synchronized by the clock, making sure everyone understands the message clearly.
Example
This example shows how to initialize I2C and send a byte of data from a master device to a slave device in Embedded C.
#include <avr/io.h> #include <util/twi.h> #define SLAVE_ADDRESS 0x50 void I2C_Init(void) { // Set clock frequency to 100kHz assuming 16MHz CPU TWSR = 0x00; // Prescaler = 1 TWBR = 72; // Bit rate register TWCR = (1 << TWEN); // Enable TWI } void I2C_Start(void) { TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN); // Send START while (!(TWCR & (1 << TWINT))); // Wait for TWINT flag } void I2C_Stop(void) { TWCR = (1 << TWINT) | (1 << TWSTO) | (1 << TWEN); // Send STOP } void I2C_Write(uint8_t data) { TWDR = data; // Load data TWCR = (1 << TWINT) | (1 << TWEN); // Start transmission while (!(TWCR & (1 << TWINT))); // Wait for completion } int main(void) { I2C_Init(); I2C_Start(); I2C_Write((SLAVE_ADDRESS << 1) | 0); // Send slave address + write bit I2C_Write(0x37); // Send data byte I2C_Stop(); while(1) {} return 0; }
When to Use
Use the I2C protocol when you need to connect multiple devices like sensors, displays, or memory chips to a microcontroller using only two wires. It is ideal for short-distance communication inside gadgets where saving pins and wiring is important.
Common real-world uses include reading temperature sensors, controlling LCD screens, or communicating with EEPROM memory in embedded systems like home appliances, wearables, and robotics.
Key Points
- I2C uses two wires: SDA for data and SCL for clock.
- One master controls communication with multiple slave devices.
- Each device has a unique address for identification.
- It is simple and efficient for short-distance device communication.
- Embedded C code controls I2C by setting registers and sending start, data, and stop signals.