0
0
Embedded Cprogramming~5 mins

Writing data to I2C device in Embedded C

Choose your learning style9 modes available
Introduction

We write data to an I2C device to send commands or information so it can perform tasks or store values.

You want to turn on an LED connected to an I2C controller.
You need to send a configuration setting to a sensor over I2C.
You want to update the display content on an I2C screen.
You need to control a motor driver via I2C commands.
Syntax
Embedded C
i2c_start();
i2c_write((device_address << 1) | I2C_WRITE);
i2c_write(register_address);
i2c_write(data);
i2c_stop();

i2c_start() begins communication.

device_address is the 7-bit I2C address of the device.

Examples
Write 0xFF to register 0x00 of device at address 0x3C.
Embedded C
i2c_start();
i2c_write((0x3C << 1) | I2C_WRITE);
i2c_write(0x00); // register

i2c_write(0xFF); // data

i2c_stop();
Send 0x01 to register 0x10 on device 0x50.
Embedded C
i2c_start();
i2c_write((0x50 << 1) | I2C_WRITE);
i2c_write(0x10); // register

i2c_write(0x01); // data

i2c_stop();
Sample Program

This program simulates writing the value 0xA5 to register 0x00 of an I2C device at address 0x3C. It prints each step to show the communication sequence.

Embedded C
#include <stdio.h>

#define I2C_WRITE 0

// Mock functions for I2C communication
void i2c_start() {
    printf("I2C Start\n");
}

void i2c_write(unsigned char data) {
    printf("Write: 0x%02X\n", data);
}

void i2c_stop() {
    printf("I2C Stop\n");
}

int main() {
    unsigned char device_address = 0x3C; // Example device
    unsigned char register_address = 0x00;
    unsigned char data = 0xA5;

    i2c_start();
    i2c_write((device_address << 1) | I2C_WRITE);
    i2c_write(register_address);
    i2c_write(data);
    i2c_stop();

    return 0;
}
OutputSuccess
Important Notes

Always shift the device address left by 1 bit and add the write bit (0) when sending the address.

Check the device datasheet for correct register addresses and data format.

Make sure to call i2c_start() before writing and i2c_stop() after finishing.

Summary

Writing data to an I2C device involves starting communication, sending the device address with write bit, the register address, the data, and then stopping communication.

Use the device's 7-bit address shifted left by one, with the least significant bit set to 0 for writing.

Always follow the device datasheet instructions for correct register and data values.