【问题标题】:Cannot read i2c device properly无法正确读取 i2c 设备
【发布时间】:2014-01-10 15:23:53
【问题描述】:

我正在尝试编写一个嵌入式 qt 应用程序来读取特定的 i2c rtc 设备。这是我初始化 i2c 的代码:

int addr = 0x68;        // The I2C address of the RTC

sprintf(filename,I2C_FILE_NAME);
if ((file = open(filename,O_RDWR)) < 0)
{
    qDebug()<<"Failed to open the bus.";
    return;
}

if (ioctl(file,I2C_SLAVE_FORCE,addr) < 0)
{
    qDebug()<<"Failed to acquire bus access and/or talk to slave.\n";
    return;
}

从设备读取:

unsigned char addr = 0x68;
unsigned char reg = 0x00;
unsigned char inbuf[2], outbuf;

struct i2c_rdwr_ioctl_data packets;
struct i2c_msg messages[2];

/*
* In order to read a register, we first do a "dummy write" by writing
* 0 bytes to the register we want to read from.  This is similar to
* the packet in set_i2c_register, except it's 1 byte rather than 2.
*/
outbuf = reg;
messages[0].addr  = addr;
messages[0].flags = 0;
messages[0].len   = sizeof(outbuf);
messages[0].buf   = &outbuf;
/* The data will get returned in this structure */
messages[1].addr  = addr;
messages[1].flags = I2C_M_RD/* | I2C_M_NOSTART*/;
messages[1].len   = 2;
messages[1].buf   = inbuf;
/* Send the request to the kernel and get the result back */
packets.msgs      = messages;
packets.nmsgs     = 2;
if(ioctl(file, I2C_RDWR, &packets) < 0)
{
    qDebug()<<"Unable to send data";
    return;
}
qDebug() << inbuf[0];

我要做的只是读取保存“秒”的 rtc 设备寄存器。我得到的是一些数字,但这些数字起初看起来不错,但有一些奇怪的增量。比如,55,56,56,57 然后跳转到64?那么它会上升到89,然后是0?我不知道为什么会发生这种情况或我的代码有什么问题?

【问题讨论】:

标签: qt embedded embedded-linux ioctl i2c


【解决方案1】:

问题是寄存器没有保存秒数的简单计数。高位保存几十秒,低位保存单位秒。

(inbuf[0] &gt;&gt; 4) &amp; 0x7; 可以获得几十秒,inbuf[0] &amp; 0xf 可以获得单位秒。

不要尝试使用qDebug() &lt;&lt; inbuf[0]; 打印秒数,而是使用类似的东西:

qDebug() << (10 * ((inbuf[0] >> 4) & 0x7) + (inbuf[0] & 0xf));

【讨论】:

  • 不知道设备怎么知道这个?
  • @MartinJames:OP 实际上并没有发布设备,所以我不确定你会读什么手册......也许 OP 和 Krueger 之前有过讨论,所以上下文是已知的,但对于像我这样的新人,它不是。这就是为什么要求澄清......
  • 设备是 RTC,ds1337。这是数据表datasheets.maximintegrated.com/en/ds/DS1337-DS1337C.pdf
  • 它可以工作,但我不明白你不知道设备怎么能理解?所有 RTC 设备都具有相同的标准吗?
  • 对时钟值使用二进制编码的十进制不是标准,但也并不罕见。如果将问题中的示例计数转换为十六进制表示,则模式很容易看到。
猜你喜欢
  • 2018-07-01
  • 1970-01-01
  • 2016-12-14
  • 2023-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-03
  • 1970-01-01
相关资源
最近更新 更多