我为Raspberry Pi购买了MCP23017,以增加GPIO引脚。

python - 使用Python从MCP23017获取信息-LMLPHP

我目前已经安装了它,我正在尝试获得我拥有的多余销钉。左侧为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)


当我尝试读取该值时,它给了我奇怪的数字,而我几乎找不到关于“十六进制”和“二进制数”的任何解释,这迫使我被淘汰。该数据表在我看来就像中文。

任何帮助将不胜感激!

最佳答案

该脚本将打开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


我在Adafruit LCD Keypad Kit上使用MCP23017,因此某些引脚被电路板拉低。

了解端口值

每个端口具有8个GPIO引脚。如果将端口的所有引脚拉高,则该端口的十六进制值为0xFF。如果某个引脚被拉低,则该引脚的位将为零。例如,如果将GPA0拉低,则GPIOA寄存器的值为0xFE:

1111 1110 = 0xFE

关于python - 使用Python从MCP23017获取信息,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41266273/

10-12 21:02