Chinaunix首页 | 论坛 | 博客
  • 博客访问: 515510
  • 博文数量: 87
  • 博客积分: 4086
  • 博客等级: 上校
  • 技术积分: 900
  • 用 户 组: 普通用户
  • 注册时间: 2007-12-23 15:55
文章分类

全部博文(87)

文章存档

2012年(3)

2010年(13)

2009年(7)

2008年(64)

我的朋友

分类: LINUX

2008-11-01 11:24:16

    花了几天的时间看Linux的I2C构架,总算明白了一点点。先把这两天完成的一个程序贴出来,和大家分享。
 
    程序基于博创的经典平台(2410和270都可以)。可以对上面的I2C接口的AT24C01进行读写。具体实现请参看源代码。

#include <stdio.h>
#include <linux/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <errno.h>
#include <assert.h>
#include <string.h>

#define I2C_RETRIES 0x0701
#define I2C_TIMEOUT 0x0702
#define I2C_RDWR 0x0707

struct i2c_msg {
    __u16 addr; /* slave address */
    __u16 flags;
    __u16 len;
    __u8 *buf; /* pointer to msg data */
};

struct i2c_rdwr_ioctl_data {
    struct i2c_msg *msgs; /* pointers to i2c_msgs */
    int nmsgs; /* number of i2c_msgs */
};

int main(int argc, char **argv)
{
    struct i2c_rdwr_ioctl_data data;
    struct i2c_msg msg;
    unsigned int fd, i, j;
    unsigned char buff[9] = {0, 0x12, 0x32, 0x46, 0xf4, 0x9f, 0xa4, 0xc8, 0x78};
    unsigned char buf2 = 0;
    unsigned char buf3[8] = {0};
    int ret;


    fd = open("/dev/i2c-0", O_RDWR);
    if (!fd)
    {     
        printf("Error on opening the device file\n");
        return 0;
    }

    data.nmsgs = 1;
    data.msgs = &msg;

    msg.addr = 0x52;
    msg.flags = 0;
    msg.len = 9;
    msg.buf = buff;
    
    ioctl(fd,I2C_TIMEOUT,5); /* set the timeout */
    ioctl(fd,I2C_RETRIES,5);
    for(i=0; i<16; i++)
    {
        buff[0] = i*8;
        buff[8]++;
        //ioctl(fd, I2C_RDWR, &data);

    }

    msg.buf = &buf2;
    msg.len = 1;
    ioctl(fd, I2C_RDWR, &data);

    msg.buf = buf3;
    msg.flags = 1;
    msg.len = 8;

    for(j=0; j<16; j++)
    {
        ioctl(fd, I2C_RDWR, &data);
    
        for(i=0; i<8; i++)    
            printf("0x%02x ", buf3[i]);
        printf("\n");    
    }

    close(fd);
    return;
}

 

程序使用的是内核提供的i2c-dev接口,利用ioctl的I2C_RDWR来产生各种需要的时序。

阅读(1745) | 评论(2) | 转发(0) |
给主人留下些什么吧!~~

qinfengbin2009-12-04 17:15:09

顶下

chinaunix网友2009-12-04 17:06:29

支持!!!好!!!www.openrd.cn