以前分析过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的日子不知道还要持续多久!!!