mcauser/micropython-mcp23017

Documentation for setting a callback

Closed this issue · 2 comments

Hello, I'm fairly new to uPython. I'm using this library for my ESP-32 and MCP23017 expander. Can you provide an example of using INTA/B for callback functions?

Answered my own question. For anyone else trying to figure out how to use the interrupt from MCP23017, here's what works for me. I'm using the ESP-32 DevKit v4 with the Expand 2 Click MCP23017 breakout

from machine import I2C, Pin
sda_pin=Pin(21)
scl_pin=Pin(22)
i2c=I2C(sda=sda_pin, scl=scl_pin)
mcp=mcp23017.MCP23017(i2c)

# this is the ESP-32 pin to get the interrupt on
int_pin=Pin(12, Pin.IN)

# callback function responding to MCP pin
mcp_cbk=lambda x : print("MCP pin interrupt")
int_pin.irq(trigger=Pin.IRQ_FALLING, handler=mcp_cbk)

# Do something here to change the state of MCP pin on port A (I have buttons) 
# get the MCP pin that triggered the interrupt
mcp.interrupt_triggered_gpio(port=0)

# reset the MCP register to capture the next trigger
mcp.interrupt_captured_gpio(port=0)

This is working for me. Maybe there's a better method of getting the interrupts from MCP23017 using this library? For now it's working great. Thanks for the useful library.

That is correct. Here's how you do it using the property interface:

from machine import I2C, Pin
sda_pin=Pin(21)
scl_pin=Pin(22)
i2c=I2C(sda=sda_pin, scl=scl_pin)
mcp=mcp23017.MCP23017(i2c)

# this is the ESP-32 pin to get the interrupt on
int_pin=Pin(12, Pin.IN)

# callback function responding to MCP pin
mcp_cbk=lambda x : print("MCP pin interrupt")
int_pin.irq(trigger=Pin.IRQ_FALLING, handler=mcp_cbk)

# configure the first 4 pins as input (1=in, 0=out)
mcp.porta.mode = 0b00001111

# enable pull ups on the first 4 pins (0=disabled, 1=enabled)
mcp.porta.pullup = 0b00001111

# enable interrupts on the first 4 pins (0=disabled, 1=enabled)
mcp.porta.interrupt_enable = 0b00001111

# Do something here to change the state of MCP pin on port A
# eg. connect pin 0 to GND with a push button or wire.

# get the MCP pin that triggered the interrupt - after reading this register, interrupts will fire again on the next pin state change.
print(mcp.porta.interrupt_flag)

# reset the MCP register to capture the next trigger
print(mcp.porta.interrupt_captured)