我只是Python的新手,目前正在使用Raspberry Pi上的I2C从数字罗盘中读取2个字节。 MSB和LSB值存储在例如
的数组中
a = [0x07, 0xFF]
我想将这两个字节加入一个变量,例如
b == 0x07FF
我将如何做到这一点?
我认为这就像将MSB乘以256并将其添加到LSB一样容易,但我不断得到" IndexError:列表索引超出范围"
任何有关这方面的帮助将不胜感激:)
我的代码是:
import smbus
import time
bus = smbus.SMBus(1)
addr = 0x1E
bus.write_byte_data(addr, 0x00, 0x70)
bus.write_byte_data(addr, 0x01, 0xA0)
bus.write_byte_data(addr, 0x02, 0x00)
time.sleep(0.006)
for i in range(0,10):
x = bus.read_i2c_block_data(addr,0x03,2)
y = bus.read_i2c_block_data(addr,0x07,2)
z = bus.read_i2c_block_data(addr,0x05,2)
xval = 256*x[2]+x[1]
print x, y, z
print xval
time.sleep(1)
print 'exiting...'
我得到的错误是:
Traceback (most recent call last):
File "compass2.py", line 18, in <module>
xval = 256*x[2]+x[1]
IndexError: list index out of range
答案 0 :(得分:1)
正如评论中所述,在Python中,索引从0开始,而不是从1.在代码中,从x[0]
开始,而不是x[1]
。
要合并0到255之间的两个整数:
信用:this answer
MAXINT = 255 # Must be a power-of-two minus one
NUM_BITS = MAXINT.bit_length()
def merge(a, b):
c = (a << NUM_BITS) | b
return c
def split(c):
a = (c >> NUM_BITS) & MAXINT
b = c & MAXINT
return a, b
# Test:
EXPECTED_MAX_NUM_BITS = NUM_BITS * 2
for a in range(MAXINT + 1):
for b in range(MAXINT + 1):
c = merge(a, b)
assert c.bit_length() <= EXPECTED_MAX_NUM_BITS
assert (a, b) == split(c)
此技术有效,但不是首选。
MAXINT_PLUS1 = 256
def merge(a, b):
c = MAXINT_PLUS1 * a + b
return c
def split(c):
a, b = divmod(c, MAXINT_PLUS1)
return a, b
# Test:
EXPECTED_MAX_NUM_BITS = (MAXINT_PLUS1 - 1).bit_length() * 2
for a in range(MAXINT_PLUS1):
for b in range(MAXINT_PLUS1):
c = merge(a, b)
assert c.bit_length() <= EXPECTED_MAX_NUM_BITS
assert (a, b) == split(c)