Reading from I2C

Viewed 1037

I am reading a 24bit value using I2C in Raspberry Pi.
I open the /dev/i2c-1 file and then reading from it using the os.read function in python.
The transaction is being carried out correctly.

enter image description here

But the problem is even though I can access the register, when I try to store the value in a variable it doesn't work. According to the documentation of os.read(), if the EOF is reached, an empty string is returned and that's exactly my problem. How can I store the correct value?

Code below:

fd = os.open(filename,os.O_RDWR) //Opens the file           
#The reason i use os.open instead of normal python open is that I
#need to access the linux C function.
def func(fd,addr):
    os.write(fd,addr) // Sets the pointer to the register to be read. 
    x = os.read(fd,3) //Reads the value from the register. 
    print x //Prints an empty string 

In order to cross check, I tried using the pigpio library. If I read using its function, it returns 2 values, count of the bytes read and the byte string itself.

What I noticed was that if I try to store the byte string, the one returned from the pigpio function, I still get an empty string when i print it on screen like this print(data).

What I think the problem is not of storing the data, but of properly formatting it .

So can anyone suggest how do I convert the byte string to an int value?

I know that there's one function for python 3. But I need to use python 2

0 Answers
Related