2017-10-12 120 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))