Chinaunix

标题: 博创经典平台上读写at24c01文件 [打印本页]

作者: yqliu29    时间: 2008-11-01 11:24
标题: 博创经典平台上读写at24c01文件
    花了几天的时间看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; i16; 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; j16; j++)
    {
        ioctl(fd, I2C_RDWR, &data);
   
        for(i=0; i8; i++)   
            printf("0x%02x ", buf3);
        printf("\n");   
    }
    close(fd);
    return;
}

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


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/57747/showart_1356446.html




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2