eeprom是用于存放小量数据的存储芯片。 at24c02就是使用i2c接口的eeprom的一种.
at24xxx eeprom的工作原理参考: http://blog.csdn.net/jklinux/article/details/74162876
dev-interface就是i2c控制器供应用程序调用的接口.不熟识的话请参考: http://blog.csdn.net/jklinux/article/details/78676741
主要的读写时序:
由上时序图可见,让eeprom在指定的位置(word address: 0 ~ 255)上存放数据(data)时, ioctl(fd, I2C_RDWR, …)函数需要调用一次, 需要一条struct i2c_msg消息.
由上时序图可见,读出eeprom在指定的位置(word address: 0 ~ 255)上存放数据时, ioctl(fd, I2C_RDWR, …)函数需要调用一次, 需要两条struct i2c_msg消息. 第一条写消息需要把要读的位置发给eeprom, 第二条读消息接收eeprom输出的数据.
实现eeprom里循环存放’A’ ~ ‘Z’字符:
/* eeprom_write.c */
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/i2c.h>
#include <linux/i2c-dev.h>
#define EEPROM_ADDR 0x50
int main(void)
{
int fd, i;
fd = open("/dev/i2c-0", O_RDWR);
if (fd < 0)
{
perror("open i2c controller");
return 1;
}
///////////////////////////////////////在eeprom里循环存放'A'--'Z'
char wdata[2];
struct i2c_msg msg = {
EEPROM_ADDR, 0, 2, wdata
};
struct i2c_rdwr_ioctl_data wdat = {
.msgs = &msg,
.nmsgs = 1,
};
for (i = 0; i < 256; i++)
{
wdata[0] = i;
wdata[1] = i%26+'A';
if (ioctl(fd, I2C_RDWR, &wdat) < 0)
{
perror("i2c rdwr failed\n");
break;
}
usleep(1000); //发出停止信号后, 在再发出开始信号前需要延时一会
}
//////////////////////////////////////
close(fd);
return 0;
}
读出eeprom里所有的内容:
/* eeprom_read.c */
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/i2c.h>
#include <linux/i2c-dev.h>
#define EEPROM_ADDR 0x50
int main(void)
{
int fd, i;
fd = open("/dev/i2c-0", O_RDWR);
if (fd < 0)
{
perror("open i2c controller");
return 1;
}
char reg, dat;
struct i2c_msg msgs[2] = {
{EEPROM_ADDR, 0, 1, ®},
{EEPROM_ADDR, I2C_M_RD, 1, &dat},
};
struct i2c_rdwr_ioctl_data rwdat = {
.msgs = msgs,
.nmsgs = 2,
};
for (i = 0; i < 256; i++)
{
reg = i;
if (ioctl(fd, I2C_RDWR, &rwdat) < 0)
{
perror("i2c rdwr failed\n");
break;
}
usleep(1000); //发出停止信号后, 在再发出开始信号前需要延时一会
if (0 == i%26)
printf("\n");
printf("%c ", dat);
}
//////////////////////////////////////
close(fd);
return 0;
}