0
0
Embedded Cprogramming~5 mins

Reading data from I2C device in Embedded C

Choose your learning style9 modes available
Introduction

Reading data from an I2C device lets your microcontroller get information from sensors or other hardware. It helps your program understand the outside world.

You want to get temperature readings from a sensor connected via I2C.
You need to read data from an EEPROM chip to retrieve stored information.
You want to get the current time from a real-time clock module using I2C.
You want to read joystick or button states from an I2C input device.
Syntax
Embedded C
int i2c_read(uint8_t device_address, uint8_t register_address, uint8_t *data, size_t length);

// device_address: I2C address of the device
// register_address: Register to read from
// data: Pointer to buffer to store read bytes
// length: Number of bytes to read
// Returns 0 on success, non-zero on failure

The function usually returns 0 if reading was successful.

You must provide a buffer to store the data read from the device.

Examples
This reads 2 bytes from register 0x00 of the device at address 0x48.
Embedded C
uint8_t buffer[2];
int status = i2c_read(0x48, 0x00, buffer, 2);
This reads 1 byte from register 0x0F of the device at address 0x68.
Embedded C
uint8_t data;
int status = i2c_read(0x68, 0x0F, &data, 1);
Sample Program

This program simulates reading 3 bytes from an I2C device at address 0x50, register 0x10. It prints the bytes in hexadecimal format.

Embedded C
#include <stdio.h>
#include <stdint.h>
#include <string.h>

// Mock I2C read function for demonstration
int i2c_read(uint8_t device_address, uint8_t register_address, uint8_t *data, size_t length) {
    // For demo, pretend device returns fixed data
    if (device_address == 0x50 && register_address == 0x10 && length == 3) {
        data[0] = 0xAB;
        data[1] = 0xCD;
        data[2] = 0xEF;
        return 0; // success
    }
    return -1; // failure
}

int main() {
    uint8_t device_addr = 0x50;
    uint8_t reg_addr = 0x10;
    uint8_t read_data[3];

    int result = i2c_read(device_addr, reg_addr, read_data, sizeof(read_data));

    if (result == 0) {
        printf("Read data: 0x%02X 0x%02X 0x%02X\n", read_data[0], read_data[1], read_data[2]);
    } else {
        printf("Failed to read from device\n");
    }

    return 0;
}
OutputSuccess
Important Notes

Always check the return value of the I2C read function to handle errors.

Make sure the buffer you provide is large enough for the number of bytes you want to read.

Device addresses and register addresses are usually given in the device datasheet.

Summary

Reading data from I2C devices lets your program get sensor or hardware info.

You provide the device address, register, and a buffer to store data.

Always check if the read was successful before using the data.