linux s3c2440 下i2c设备(EEPROM)操作

以前分析过i2c总线的构架但没写过i2c设备驱动,在platform下i2c实现比裸机复杂的多,由于内核中已加入i2c的实现且有虚拟设备i2c-0,因此借助内核,直接写应用程序就可以完成对i2c设备的操作。

root@FZ:/dev# ls
apm_bios            ptyv1               ttyp9
audio               ptyv2               ttypa
i2c-0   

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/i2c.h>
#include <linux/i2c-dev.h>

#define PAGE_SIZE  64
#define SLAVE_ADDR 0x50
#define I2C_DEV   "/dev/i2c-0"

static int read_eeprom(int fd, char *buff, int count, int addr)
{
    int res;
    if(write(fd, &addr, 1) != 1)
    {
        printf("Can't write %s's addr %d...\n", I2C_DEV, addr);
        return -1;
    }
    res = read(fd, buff, count);
    printf("Read %d bytes at %x ...\n", res, addr);
    return res;
}

static int write_eeprom(int fd, char *buf, int count, int addr)
{
    int res;
    int i;
    static char temp[PAGE_SIZE+1];

    memcpy(temp+1, buf, count);
    temp[0] = addr;
    res = write(fd, temp, count+1);
    printf("Write %d bytes at %x ...\n",res-1, addr);
    return res;
}
        

int main(int argc, char *argv[])
{
    int fd;
    char buf[PAGE_SIZE];
    int i;

    fd = open(I2C_DEV, O_RDWR);

    ioctl(fd, I2C_TENBIT, 0);
    ioctl(fd, I2C_SLAVE, SLAVE_ADDR);

    memset(buf, 0xAA, PAGE_SIZE);
    write_eeprom(fd, buf, PAGE_SIZE, 0);

    memset(buf, 0x00, PAGE_SIZE);
    read_eeprom(fd, buf, PAGE_SIZE, 0);

    for(i = 0; i < PAGE_SIZE; i++)
        printf("The %d nuber is %d\n", i, buf[i]);
    printf("Enjoy!!!");
    
    close(fd);
    return 0;
}
上面的write_eeprom写受eeprom页大小的限制,比如页大小为16byte,则写入的最大字节数为16,一般小于16,这与起始写的地址有关,可以自己写个接口函数实现无限制的读写,这里仅给出示例以便于明白实现的一种手法。困了,睡觉了,白天dsp晚上arm的日子不知道还要持续多久!!!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值