I2C EEPROM:可以写,但只能读0xFF



我目前正在研究i.MX6 (Android BSP)和24C08WP EEPROM之间的I2C通信。

我在i.MX6上运行一个以前在Linux下的NDK下编译的二进制文件。

我检测到通过i2cdetect工具连接到i.MX6的I2C总线(地址0x50)的NTAG 5组件。

使用以下代码,我可以执行写入操作,我可以使用Arduino板和I2C读取操作进行检查。

但是,当我在i.MX6下对用户空间执行读操作时,我只得到0xFF值。

下面是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <linux/i2c-dev.h>
#include "board.h"
#include "debug_tools.h"
#include "boardselection.h"
int main(void) {
int file;
int adapter_nr = 1; /* probably dynamically determined */
char filename[20];
snprintf(filename, 19, "/dev/i2c-%d", adapter_nr);
file = open(filename, O_RDWR);
if (file < 0) {
/* ERROR HANDLING; you can check errno to see what went wrong */
exit(1);
}
int addr = 0x50; /* The I2C address */
if (ioctl(file, I2C_SLAVE, addr) < 0) {
/* ERROR HANDLING; you can check errno to see what went wrong */
exit(1);
}
uint8_t reg = 0x00;
uint8_t data_w[4] = {0x00, 0x00, 0x00, 0x00};
data_w[0] = reg;
data_w[1] = 0x01;
data_w[2] = 0x02;
data_w[3] = 0x03;

/* Write the register */
if (write(file, data_w, 4) != 4)
{
perror("Failed to write to the i2c bus");
exit(1);
}
usleep(2000000);
uint8_t data_r[4] = {0x00, 0x00, 0x00, 0x00};
if (read(file, data_r, 3) != 3) {
/* ERROR HANDLING: i2c transaction failed */
perror("Failed to read register value");
exit(1);
}
/* data_r[0] contains the read byte */
printf("%X %X %Xn", data_r[0], data_r[1], data_r[2]);
return 0;
}

你能帮我吗?

这个线程描述了关于接收0xFF值的几乎相同的问题。

正如@Andrew Cottrell在这个线程中所说的:"从你的I2C设备中读取,假设它使用一个字节的寄存器,写一个字节的缓冲区(寄存器地址),然后读取一个或多个字节的缓冲区(在该寄存器和后续寄存器的值)。">

所以正确的代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <linux/i2c-dev.h>
#include "board.h"
#include "debug_tools.h"
#include "boardselection.h"
int main(void) {
int file;
int adapter_nr = 1; /* probably dynamically determined */
char filename[20];
snprintf(filename, 19, "/dev/i2c-%d", adapter_nr);
file = open(filename, O_RDWR);
if (file < 0) {
/* ERROR HANDLING; you can check errno to see what went wrong */
exit(1);
}
int addr = 0x50; /* The I2C address */
if (ioctl(file, I2C_SLAVE, addr) < 0) {
/* ERROR HANDLING; you can check errno to see what went wrong */
exit(1);
}
uint8_t reg = 0x00;
uint8_t data_w[4] = {0x00, 0x00, 0x00, 0x00};
data_w[0] = reg;
data_w[1] = 0x44;
/* Write the register */
if (write(file, data_w, 2) != 2)
{
perror("Failed to write to the i2c bus");
exit(1);
}
usleep(1000000);
uint8_t data_r[4] = {0x00, 0x00, 0x00, 0x00};
if (write(file, &reg, 1) != 1)
{
perror("Failed to write to the i2c bus");
exit(1);
}
if (read(file, data_r, 1) != 1) {
/* ERROR HANDLING: i2c transaction failed */
perror("Failed to read register value");
exit(1);
}
/* data_r[0] contains the read byte: 0x44 */
printf("%02Xn", data_r[0]);
return 0;
}

注意::如果不使用usleep()在两次写操作之间等待,则第二次写操作可能会失败。

相关内容

最新更新