#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#include <fcntl.h>
#include <errno.h>
#include <linux/i2c.h>
#include <linux/i2c-dev.h>
#include <unistd.h>
#include<sys/stat.h>
#include<errno.h>

#include <sys/ioctl.h>

int main(int argc, char *argv[])
{
    struct i2c_msg i2cmsg[2];
    unsigned char data_index = 128;
    unsigned char data_space = 0;
        i2cmsg[0].addr = 0x0d;
        i2cmsg[0].flags = 0;
        i2cmsg[0].len = sizeof(data_index);
        i2cmsg[0].buf = &data_index;

        i2cmsg[1].addr = 0x0d;
        i2cmsg[1].flags = I2C_M_RD;
        i2cmsg[1].len = sizeof(data_space);
        i2cmsg[1].buf = &data_space;

    struct i2c_rdwr_ioctl_data msg_rdwr;
    msg_rdwr.msgs = i2cmsg;
    msg_rdwr.nmsgs = 2;
    int file=open("/dev/i2c-1",O_RDWR);
    if (file < 0) {
           /* ERROR HANDLING: you can check errno to see what went wrong */
            perror("Failed to open the i2c bus");
                exit(1);
        }
    int result_2 = ioctl(file, I2C_SLAVE, 0x0d);
        if (result_2 < 0) {
            printf("Failed to acquire bus access and/or talk to slave.\n");
            /* ERROR HANDLING; you can check errno to see what went wrong */
                exit(1);
        }


   int result_1 = ioctl(file, I2C_RDWR, &msg_rdwr);
    if (result_1 < 0) {
        printf("Failed to acquire bus access and/or talk to slave.\n");
        /* ERROR HANDLING; you can check errno to see what went wrong */
            exit(1);
    }

        printf("0x%02X\n",data_space);
        close(file);
        return 0;
}

