2014-01-10 117 views
0

我正在尝试编写一个读取特定i2c rtc设备的嵌入式qt应用程序。这里是我的代码来初始化I2C:无法正确读取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?我不知道为什么会发生这种情况,或者我的代码有什么问题?

+0

哇,使用qDebug()代替了printf()在打印的非Qt代码....这是一个真正的奇怪的想法。 :-) – lpapp

+0

哪个i2c设备是这个? – lpapp

+0

它是一个RTC,ds1337。这里是数据表http://datasheets.maximintegrated.com/zh/ds/DS1337-DS1337C.pdf – thehilmisu

回答

2

问题是寄存器不能保持秒数的简单计数。高位保持数十秒,低位保持单位秒。

(inbuf[0] >> 4) & 0x7;可以得到几十秒,用inbuf[0] & 0xf可以得到单位秒。

,而不是试图与qDebug() << inbuf[0];打印秒,使用类似:

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

你怎么知道这不知道设备? – lpapp

+0

他阅读用户手册? –

+0

@MartinJames:OP实际上并没有发布这个设备,所以我不确定你会阅读哪些手册......也许OP和Krueger之前有过讨论,所以背景知道了,但对于像我这样的新人来说,不是这样。这就是为什么要求澄清... – lpapp