Reputation: 43
This is my first question in Stackoverflow if I have made a mistake while writing this question please give me a feedback to correct myself.
I want to use i2c communication for my raspberry pi. I want to use python-periphery(I know there is smbus out there). In the documentation https://python-periphery.readthedocs.io/en/latest/i2c.html there is not much information how to use the library. Here is the code in the documentation:
from periphery import I2C
# Open i2c-0 controller
i2c = I2C("/dev/i2c-0")
# Read byte at address 0x100 of EEPROM at 0x50
msgs = [I2C.Message([0x01, 0x00]), I2C.Message([0x00], read=True)]
i2c.transfer(0x50, msgs)
print("0x100: 0x{:02x}".format(msgs[1].data[0]))
i2c.close()
I have tried to write/read with a sensor and It was successful. However in my test code I used this:
#Write to 0x09 register,this byte: 0x13
W9 = [I2C.Message([0x09,0x13])]
i2c.transfer(DFLT_ADDRESS,W9)
#Read from 0x09 register
R = [I2C.Message([0x09]), I2C.Message([0x00], read=True)]
i2c.transfer(DFLT_ADDRESS,R)
print(R[1].data[0])
(I have used smbus to check the data is written in the register and read correctly. So, test code is working.)
What I want to know is where is the 0x100(I think [0x01, 0x00] this is 0x100) in this line: msgs = [I2C.Message([0x01, 0x00]), I2C.Message([0x00], read=True)]
, And when i tried this, it writes 0x00 to the register in my sensor. Is it beause my sensor has 8 bit but I tried to write 16 bit? So, Can anyone explain what is going on in the documentation example?
Upvotes: 3
Views: 1802
Reputation: 31
Maybe you could try this code I use on my raspberry pi zero :
# coding=utf-8
# date : 25/05/2021
# dossier : piPeri
# fichier : pP_readByte01.py
# check the result with these commands :
# i2cset -y 1 0x51 0x10 0x01
# i2cget -y 1 0x51
# 3x times
from periphery import I2C
print(" Read 3 bytes starting at register address 0x1001 of EEPROM at I2C address 0x51 ")
# Open i2c-0 controller
i2c = I2C("/dev/i2c-1")
# create array to hold received data ( 3 bytes in my case )
dataRX = [0,0,0]
# create message to place 16 bits in memory register of eeprom
msgWritePointer = I2C.Message([0x10,0x01],read=False)
# create message to read data according to length of array 'dataRX'
msgRead = I2C.Message(dataRX,read=True)
# messages are assembled, order is important
msgs = [msgWritePointer, msgRead]
# call transfer function
i2c.transfer(0x51, msgs)
# print received bytes
for i in range(0,len(msgs[1].data)):
print(hex(msgs[1].data[i]))
i2c.close()
Upvotes: 3