2016-12-21 83 views
1

我爲我的Raspberry Pi購買了一個MCP23017來增加GPIO引腳。從Python獲取MCP23017的信息

enter image description here

我目前已經安裝了它,我試圖讓我有額外的引腳; GPB0-GPB7在左側,GPA0-GPA7在右側進行我的競標。

我需要將它們設置爲輸入引腳來讀取高,低狀態,並添加上拉電阻器到他們,但是這是據我已經得到了:

import smbus 
import time 

bus = smbus.SMBus(1) # As I'm using an newer RPi. 

DEVICE = 0x20 # this is what it shows when I check it. 
IODIRA = 0x00 
GPIOA = 0x12 

bus.write_byte_data(DEVICE,IODIRA,0xFF) 
bus.write_byte_data(DEVICE,0x0C,0xff) 

value = bus.read_byte_data(DEVICE,GPIOA) 

當我嘗試閱讀價值,它給了我奇怪的數字,我幾乎無法找到關於Hexidecimals和Binary數字的任何解釋,並且它強迫我離開。數據表看起來像中國人對我..

任何幫助真的很感謝!

+0

您是否在A0,A1和A2上拉電阻? –

+0

A0 A1和A2全部3接地。 – user5740843

+0

您可能必須在'IOCON'寄存器中設置'SEQOP'位。默認情況下,順序操作被啓用,這會增加地址指針。另外,「sudo i2cdetect -y 0」和「sudo i2cdetect -y 1」的輸出是什麼? –

回答

1

該腳本將打開GPIOA和GPIOB的內部上拉電阻。然後它會每秒打印一次所有寄存器的值。在更改輸入時,可以使用輸出來觀察寄存器值的變化。

import smbus 
import time 

DEVICE = 0x20 

address_map = { 
    0x00: 'IODIRA', 0x01: 'IODIRB', 0x02: 'IPOLA', 0x03: 'IPOLB', 
    0x04: 'GPINTENA', 0x05: 'GPINTENB', 0x06: 'DEFVALA', 0x07: 'DEVFALB', 
    0x08: 'INTCONA', 0x09: 'INTCONB', 0x0a: 'IOCON', 0x0b: 'IOCON', 
    0x0c: 'GPPUA', 0x0d: 'GPPUB', 0x0e: 'INTFA', 0x0f: 'INTFB', 
    0x10: 'INTCAPA', 0x11: 'INTCAPB', 0x12: 'GPIOA', 0x13: 'GPIOB', 
    0x14: 'OLATA', 0x15: 'OLATB' 
} 
register_map = {value: key for key, value in address_map.iteritems()} 
max_len = max(len(key) for key in register_map) 

def print_values(bus): 
    print "-" * 20 
    for addr in address_map: 
     value = bus.read_byte_data(DEVICE, addr) 
     print "%-*s = 0x%02X" % (max_len, address_map[addr], value) 

bus = smbus.SMBus(1) 
bus.write_byte_data(DEVICE, register_map['GPPUA'], 0xFF) 
bus.write_byte_data(DEVICE, register_map['GPPUB'], 0xFF) 

counter = 0 
try: 
    while True: 
     print_values(bus) 
     counter += 1 
     print "counter = %s" % counter 
     time.sleep(1.0) 
except KeyboardInterrupt: 
    print "Keyboard interrupt" 

示例輸出

-------------------- 
IODIRA = 0xFF 
IODIRB = 0xFF 
IPOLA = 0x00 
IPOLB = 0x00 
GPINTENA = 0x00 
GPINTENB = 0x00 
DEFVALA = 0x00 
DEVFALB = 0x00 
INTCONA = 0x00 
INTCONB = 0x00 
IOCON = 0x00 
IOCON = 0x00 
GPPUA = 0xFF 
GPPUB = 0xFF 
INTFA = 0x00 
INTFB = 0x00 
INTCAPA = 0x00 
INTCAPB = 0x00 
GPIOA = 0xFF 
GPIOB = 0xE9 
OLATA = 0x00 
OLATB = 0x00 
counter = 3 

我使用MCP23017上Adafruit LCD Keypad Kit,所以一些銷正在由板拉低。

瞭解端口值

每個端口有8個GPIO引腳。如果某個端口的所有引腳都被拉高,則該端口的十六進制值將爲0xFF。如果一個引腳拉低,該引腳的位將爲零。例如,如果將GPA0拉低,則GPIOA寄存器的值將爲0xFE:

1111 1110 = 0xFE 
+0

謝謝你!當我用GND接觸一些A或B引腳時,我可以看到這些值發生了變化。有沒有辦法檢測哪些引腳連接到GND? – user5740843

+0

我添加了有關如何讀取端口值的部分。 –