【问题标题】:DS1338 i2c Read issueDS1338 i2c 读取问题
【发布时间】:2017-08-21 15:05:57
【问题描述】:

您好,我正在尝试使用我的 linux 单板计算机从 RTC-DS1338 读取时间,但我的代码有问题。我正在用它读取错误的输出。

我尝试使用i2cget -y 0 0x68 0 阅读它有效。但我的代码没有。

谁能帮帮我?

#include <stdio.h>
#include <fcntl.h>
#include <linux/i2c-dev.h>
#include <errno.h>

#define I2C_ADDR 0x68

int main (void) 
{

char value;
int fd;
unsigned char pData[10];
char i;

    if ((fd = open("/dev/i2c-0", O_RDWR)) < 0)
    {
            printf("Error: Couldn't open device! %d\n", fd);
            return 1;
    }

    if (ioctl(fd, I2C_SLAVE, I2C_ADDR) < 0)
    {
            printf("Error: Couldn't find device on address!\n");
            return 1;
    }   

    while (1) 
    {

        if (read(fd, &pData, 4) != 4)
        {
            perror("Read conversion");
        }
        else
        {
            for(i=0;i<4;i++) printf(" %02x ",(pData[i] & 0xFF));    
            printf("\n");
        }

        sleep(2);

    }

    return 0;
}

输出错误:

 00  b3  49  47
 4e  27  09  21
 24  81  29  00
 1a  20  02  10
 16  1e  1a  46
 1a  00  96  18
 45  82  03  e0
 24  40  88  1c

良好的数据:

 00  05  08  00
 01  05  08  00
 02  05  08  00
 03  05  08  00
 04  05  08  00
 05  05  08  00

【问题讨论】:

  • 好的数据是什么样的?
  • 我已经添加了好的数据输出。秒应该增加有意义

标签: linux i2c


【解决方案1】:

我已经用下面的代码解决了我的问题

if ((fd = open("/dev/i2c-0", O_RDWR)) < 0)
{
        printf("Error: Couldn't open device! %d\n", fd);
        return 1;
}

if (ioctl(fd, I2C_SLAVE, I2C_ADDR) < 0)
{
        printf("Error: Couldn't find device on address!\n");
        return 1;
}

if (write(fd, wData, 1) != 1)
{
    perror("Write to register");
}

if (read(fd, rData, 64) != 64)
{
    perror("Read conversion");
}
else
{
    memcpy(Dat,rData,7);
}

close(fd);


return 0;

【讨论】:

  • 如果您希望这是一个有用的答案,至少解释一下您的不同之处并显示更多代码会有所帮助(以前的版本没有wDatarData)。我猜是 write() 电话真正让事情开始在这里工作?
猜你喜欢
  • 2020-11-04
  • 1970-01-01
  • 1970-01-01
  • 2019-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-09
  • 1970-01-01
相关资源
最近更新 更多