2017-10-12 122 views
0

我只是Python新手,目前使用Raspberry Pi上的I2C从数字指南针读取2个字节。 MSB和LSB值被存储在一个阵列中,例如
a = [0x07, 0xFF]在Python中加入两个十六进制值

我想这两个字节连接成一个变量,如
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 
+2

Python的指标在0更改启动'XVAL = 256 * x [2] + x [1]'到'xval = 256 * x [1] + x [0]' – eyllanesc

回答

0

正如评论指出的那样,在Python,索引1处从0开始,而不是在你的代码,开始在x[0],不是x[1]

def merge(a, b): 
    return 256 * a + b 

要检索他们回来:

从0到255合并两个整数

def split(c): 
    return divmod(c, 256) 

测试:

for a in range(256): 
    for b in range(256): 
     assert (a, b) == split(merge(a, b))