#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include "linux/i2c-dev.h"
int main(int argc, char *argv[]){
int file;
int adapter_nr = 2;
char filename[20];
int addr = 0x40;
__u8 reg = 0x10;
__s32 res;
char buf[10];
snprintf(filename, 19, "/dev/i2c-%d", adapter_nr);
file = open(filename, O_RDWR);
if (file < 0) {
exit(1);
}
if (ioctl(file, I2C_SLAVE, addr) < 0) {
exit(1);
}
buf[0] = reg;
buf[1] = 0x43;
buf[2] = 0x65;
if (write(file, buf, 3) != 3) {
}
if (read(file, buf, 1) != 1) {
} else {
printf("recv data:%d\n",buf[0]);
}
#if 0
res = i2c_smbus_read_word_data(file, reg);
if (res < 0) {
} else {
}
#endif
return 0;
}
- so-called combined transactions
#include <stdio.h>
#include <linux/types.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <errno.h>
#include <string.h>
#define I2C_RETRIES 0x0701
#define I2C_TIMEOUT 0x0702
#define I2C_RDWR 0x0707
struct i2c_msg
{
unsigned short addr;
unsigned short flags;
#define I2C_M_TEN 0x0010
#define I2C_M_RD 0x0001
unsigned short len;
unsigned char *buf;
};
struct i2c_rdwr_ioctl_data
{
struct i2c_msg *msgs;
int nmsgs;
};
#define SLAVE_ADDRESS 0x50
#define ADAPTER_NR 1
int main(int argc, char *argv[])
{
struct i2c_rdwr_ioctl_data e2prom_data;
int fd,ret = 0;
char filename[16] = {0};
snprintf(filename, 15, "/dev/i2c-%d", ADAPTER_NR);
fd=open(filename,O_RDWR);
if(fd < 0)
{
perror("open error");
}
ioctl(fd,I2C_TIMEOUT,1);
ioctl(fd,I2C_RETRIES,2);
e2prom_data.nmsgs=1;
e2prom_data.msgs=(struct i2c_msg*)malloc(e2prom_data.nmsgs*sizeof(struct i2c_msg));
if(!e2prom_data.msgs)
{
perror("malloc error");
exit(1);
}
(e2prom_data.msgs[0]).len=2;
(e2prom_data.msgs[0]).addr=SLAVE_ADDRESS;
(e2prom_data.msgs[0]).flags=0;
(e2prom_data.msgs[0]).buf=(unsigned char*)malloc(2);
(e2prom_data.msgs[0]).buf[0]=0x10;
(e2prom_data.msgs[0]).buf[1]=0x58;
ret=ioctl(fd,I2C_RDWR,(unsigned long)&e2prom_data);
if(ret<0)
{
perror("ioctl error1");
}
free((e2prom_data.msgs[0]).buf);
(e2prom_data.msgs[0]).buf = NULL;
free(e2prom_data.msgs);
e2prom_data.msgs = NULL;
sleep(1);
e2prom_data.nmsgs=2;
e2prom_data.msgs=(struct i2c_msg*)malloc(e2prom_data.nmsgs*sizeof(struct i2c_msg));
if(!e2prom_data.msgs)
{
perror("malloc error");
exit(1);
}
(e2prom_data.msgs[0]).len=1;
(e2prom_data.msgs[0]).addr=SLAVE_ADDRESS;
(e2prom_data.msgs[0]).flags=0;
(e2prom_data.msgs[0]).buf[0]=0x10;
(e2prom_data.msgs[1]).len=1;
(e2prom_data.msgs[1]).addr=0x50;
(e2prom_data.msgs[1]).flags=I2C_M_RD;
(e2prom_data.msgs[1]).buf=(unsigned char*)malloc(32);
memset((e2prom_data.msgs[1]).buf,0,32);
ret=ioctl(fd,I2C_RDWR,(unsigned long)&e2prom_data);
if(ret<0)
{
perror("ioctl error2");
}
printf("buff[0]=%x/n",(e2prom_data.msgs[1]).buf[0]);
free((e2prom_data.msgs[1]).buf);
free(e2prom_data.msgs);
e2prom_data.msgs = NULL;
close(fd);
return 0;
}