测试iic的代码(from 设备驱动开发详解)
#include
#include
#include
#include
#include
//#include
#define I2C_RETRIES 0x0701
#define I2C_TIMEOUT 0x0702
#define I2C_SLAVE 0x0703
#define BUF_SIZE 1024
void percentage(int given,int total){
static int first = 0;
int i;
int tmp;
total--;
tmp = (given*100)/total;
if(first != 0){ //第一次调用此显示进度的函数不应该退格
for(i=0;i<4;i++)
putchar('\b');
// fflush(stdout);
}
first = 1;
printf("%3d",tmp);putchar('%');
fflush(stdout);
}
union data{
unsigned short addr;
unsigned char byte[2];
}my_data;
main(argc, argv)
{
int fd,i,j,ret;
unsigned char *buf;
buf = malloc(BUF_SIZE);
memset(buf,0x98,BUF_SIZE);
fd = open("/dev/i2c/0",O_RDWR);
if(fd < 0){printf("open\n");return 0;}
ioctl(fd,I2C_SLAVE,0x50); //0xa0>>1 = 0x50,驱动里面会把最地位补全的(读或者写)
ioctl(fd,I2C_TIMEOUT,1);
ioctl(fd,I2C_RETRIES,1);
int block;
for(block=0;block<4;block++){
ioctl(fd,I2C_SLAVE,0x50 | block);
printf("\nwrite block:%d\n",block);
for(i=0;i<256;i++){
my_data.addr = (unsigned short)i;
my_data.byte[1] = buf[(block<<8)+i];
write(fd,&my_data.addr,2);
percentage(i,256);
usleep(10000); //怕写的时间不够,应该没问题
}
}
printf("\n\nclear buffer with 0\n");
memset(buf,0,BUF_SIZE);
printf("read from chip now\n");
for(block=0;block<4;block++){
ioctl(fd,I2C_SLAVE,0x50 | block);
printf("\nread block:%d\n",block);
for(i=0;i<256;i++){
unsigned addr;
addr = (unsigned char)i;
write(fd,&addr,1);
read(fd,&buf[(block<<8)+i],1);
percentage(i,256);
}
}
printf("\nprintf now\n");
for(i = 0; i < BUF_SIZE; i++)
{
if( (i % 16) == 0 )
printf("\n %.4x| ", i);
else if( (i % 8) == 0 )
printf(" ");
printf("%.2x ", buf[i]);
}
putchar('\n');
free(buf);
return 0;
}
阅读(2210) | 评论(0) | 转发(0) |