1
import smbus
import time
import datetime

#SMBus(0) - Raspberry Pi Model A
#SMBus(1) - Raspberry Pi Model B

bus = smbus.SMBus(1)

#I2C address of sensor
address = 0x27
def temp():

     #rvalue0 = bus.read_word_data(address,0)
     rvalue0= bus.read_i2c_block_data(address,1,32)
     print rvalue0
     print ('\n')
     rvalue1 = (rvalue0 & 0x0000ff00) >> 8
     print rvalue1
     print ('\n')
     rvalue2 = rvalue0 & 0x0000ff00
     print rvalue2
     rvalue = (((rvalue2 *256) + rvalue1) >> 2 ) *.007631
     print rvalue

Output:

[79, 202, 104, 29, 63, 41, 160, 116, 252, 166, 129, 211, 242, 154, 7, 79, 202, 104, 29, 63, 41, 160, 116, 252, 166, 129, 211, 242, 154, 7, 79, 202]

Error Message:

Traceback (most recent call last):
  File "/home/pi/temp1.py", line 41, in <module>
    temp()
  File "/home/pi/temp1.py", line 18, in temp
    rvalue1 = (rvalue0 & 0x0000ff00) >> 8
TypeError: unsupported operand type(s) for &: 'list' and 'int'
  • 1
    This isn't really a Pi question. You need to look up the difference in Python between lists and numbers. You need to study the different SMBus commands and use those appropriate to your sensor. – joan Jan 22 '16 at 12:05
  • I believe these are the (very minimal) docs for python's smbus. Your parameters look wrong. – goldilocks Jan 22 '16 at 17:12
  • i had real command but still i can not understand how to decode block of data into byte of data. and thanks – Swetank Patel Jan 23 '16 at 6:11
1

As Joan mentioned, you seem to misunderstand the return value provided by read_i2c_block_data(). According to the documentation, and your output, it returns a long[]. The & operator ands a single value. Instead of a single value, you've given it a list (containing 32) of values.

If you want to add that operation onto every member of that list, a map function is probably your best bet. I've given an example for your first operation.

def temp():
    rvalue0 = bus.read_i2c_block_data(address,1,32)
    print rvalue0
    print ('\n')
    rvalue1 = list(map((lambda x: (x & 0x0000ff00) >> 8), rvalue0))
    print rvalue1
  • i want to read 4 byte of data in that first 2 byte is humidity and other 2 for temp. how can i decode that – Swetank Patel Jan 23 '16 at 6:16
  • The documentation sucks, so I can't quite say for sure, but it looks like you're currently reading 32 bytes in your read function. Switch that to four, and then access the first element as rvalue0[0]. You can increment the number in the brackets to access each item in the array. – Jacobm001 Jan 25 '16 at 4:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.