linux dev-c,测试Linux 内核中的I2c-dev.c

原文:http://hi.baidu.com/jjhopeforever/item/4e5e75c6156aa42ea1b50a67

/************************************

此程序在linux 2.6.18的版本里面测试通过。

***************************************************************/

#include

#include

#include

#include

#include

#include

#include

#include

#define I2C_RETRIES 0x0701

#define I2C_TIMEOUT 0x0702

#define I2C_RDWR 0x0707

/*********定义struct i2c_rdwr_ioctl_data和struct i2c_msg,要和内核一致*******/

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;

/* nmsgs这个数量决定了有多少开始信号,对于“单开始时序”,取1*/

};

/***********主程序***********/

int main()

{

int fd,ret;

struct i2c_rdwr_ioctl_data e2prom_data;

fd=open("/dev/i2c-0",O_RDWR);

/*

dev/i2c-0是在注册i2c-dev.c后产生的,代表一个可操作的适配器。如果不使用i2c-dev.c

*的方式,就没有,也不需要这个节点。

*/

if(fd<0)

{

perror("open error");

}

e2prom_data.nmsgs=2;

/*

*因为操作时序中,最多是用到2个开始信号(字节读操作中),所以此将

*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);

}

ioctl(fd,I2C_TIMEOUT,100);/*超时时间*/

ioctl(fd,I2C_M_TEN,0);/*超时时间*/

ioctl(fd,I2C_RETRIES,2);/*重复次数*/

/***write data to e2prom**/

e2prom_data.nmsgs=1;

(e2prom_data.msgs[0]).len=2; //1个 e2prom 写入目标的地址和1个数据

(e2prom_data.msgs[0]).addr=0x5c;//e2prom 设备地址

(e2prom_data.msgs[0]).flags=0; //write

(e2prom_data.msgs[0]).buf=(unsigned char*)malloc(2);

(e2prom_data.msgs[0]).buf[0]=0x01;// e2prom 写入目标的地址

(e2prom_data.msgs[0]).buf[1]=0x74;//the data to write

ret=ioctl(fd,I2C_RDWR,(unsigned long)&e2prom_data);

if(ret<0)

{

perror("ioctl error1");

}

sleep(1);

/******read data from e2prom*******/

e2prom_data.nmsgs=2;

(e2prom_data.msgs[0]).len=1; //e2prom 目标数据的地址

(e2prom_data.msgs[0]).addr=0x5c; // e2prom 设备地址

(e2prom_data.msgs[0]).flags=0;//write

(e2prom_data.msgs[0]).buf[0]=0x01;//e2prom数据地址

(e2prom_data.msgs[1]).len=1;//读出的数据

(e2prom_data.msgs[1]).addr=0x5c;// e2prom 设备地址

(e2prom_data.msgs[1]).flags=I2C_M_RD;//read

(e2prom_data.msgs[1]).buf=(unsigned char*)malloc(1);//存放返回值的地址。

(e2prom_data.msgs[1]).buf[0]=0;//初始化读缓冲

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]);

/***打印读出的值,没错的话,就应该是前面写的0x74了***/

close(fd);

return 0;          }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值