PDA

View Full Version : I2C control question



cooper
8th March 2012, 22:16
Hi everyone,

I am currently writing a program on Qt to communicate RTC (DS1307) for my Gumstix Overo project. (My final goal is to let Gumstix talk to PIC)

Here is my code:



// for i2c test
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <linux/i2c-dev.h>

void MainScr::on_pushButton_11_clicked()
{
int i2c;
int ioc;
unsigned char buf[2];

if ((i2c = open("/dev/i2c-3", O_RDWR)) < 0)
ui->label_i2c_rd->setText("- " + QString::number(i2c));
else
ui->label_i2c_rd->setText("+ " + QString::number(i2c));

// tell the driver we want the device with address 0x68 on the I2C bus
if ((ioc = ioctl(i2c, I2C_SLAVE, 0x68)) < 0)
ui->label_i2c_rd_2->setText("- " + QString::number(ioc));
else
ui->label_i2c_rd_2->setText("+" + QString::number(ioc));

// write 5 to register 0x03
buf[0] = 0x03; // register address
buf[1] = 0x05; // register value
write(i2c, buf, 2);

// read 1 bytes from register 0x03
read(i2c, buf, 1);
ui->label_i2c_rd_3->setText("Today is: " + QString::number(buf[0]));
//i2c = close();
}


After run the program, i got i2c > 0. this means i2c-3 opened.
However, I got ioc = 0. is this value correct?

and also, the value in register 0x03 is always 3, not 5.

Can anyone point out where i got wrong in my program please?
Thanks in advance.

ChrisW67
9th March 2012, 01:11
After run the program, i got i2c > 0. this means i2c-3 opened.
If you say so.

However, I got ioc = 0. is this value correct?
It indicates success according to my man pages.


and also, the value in register 0x03 is always 3, not 5.
With your read, how does the device know to return register 3? Does it return the last register written? Do you need to send another device/register address?

bhamadicharef
13th June 2012, 09:53
Hi

I would be interested to learn how to setup the Qt environment on the Gumstix Overo.
As for the I2C issue, google returns lots of pages about I2C communication ...

Brahim

droneone
14th June 2012, 01:43
Just a point here...

You put data into a buffer, then call write() without checking its return value, and then call read() with the same buffer without checking its return value. Then, you happen to print out the first byte which just happens to have the exact same value as the first byte you wrote into the buffer. Why not check the return value of read() to see how many bytes were actually read from the file?