If I use this python script
Output is
so the mcp23017 is working correctly
Code:
cat test.py import smbus2import RPi.GPIO as GPIOimport time# I2C and GPIO setupI2C_BUS = 11 # Typically bus 1 is used on Raspberry PiMCP23017_ADDRESS = 0x20 # Default I2C address for MCP23017INTERRUPT_PIN = 18 # GPIO pin on Raspberry Pi for MCP23017 interrupt# MCP23017 RegistersIODIRA = 0x00 # Direction register for port AIODIRB = 0x01 # Direction register for port BGPINTENA = 0x04 # Interrupt-on-change for port AGPINTENB = 0x05 # Interrupt-on-change for port BDEFVALA = 0x06 # Default compare value for port ADEFVALB = 0x07 # Default compare value for port BINTCONA = 0x08 # Interrupt control for port AINTCONB = 0x09 # Interrupt control for port BGPPUA = 0x0C # Pull-up resistors for port AGPPUB = 0x0D # Pull-up resistors for port BGPIOA = 0x12 # GPIO register for port AGPIOB = 0x13 # GPIO register for port BINTFA = 0x0E # Interrupt flag for port AINTFB = 0x0F # Interrupt flag for port B# Initialize SMBusi2c = smbus2.SMBus(I2C_BUS)# MCP23017 Configurationdef configure_mcp23017(): # Set all pins on port A as inputs i2c.write_byte_data(MCP23017_ADDRESS, IODIRA, 0xFF) # Enable pull-up resistors on port A i2c.write_byte_data(MCP23017_ADDRESS, GPPUA, 0xFF) # Enable interrupt-on-change for all pins on port A i2c.write_byte_data(MCP23017_ADDRESS, GPINTENA, 0xFF) # Configure interrupts to compare against the previous value i2c.write_byte_data(MCP23017_ADDRESS, INTCONA, 0x00)# Interrupt Handlerdef handle_interrupt(channel): # Read interrupt flags int_flags = i2c.read_byte_data(MCP23017_ADDRESS, INTFA) # Read current GPIO state gpio_state = i2c.read_byte_data(MCP23017_ADDRESS, GPIOA) print(f"Interrupt detected! Flags: {bin(int_flags)}, GPIO state: {bin(gpio_state)}")# GPIO SetupGPIO.setmode(GPIO.BCM)GPIO.setup(INTERRUPT_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)GPIO.add_event_detect(INTERRUPT_PIN, GPIO.FALLING, callback=handle_interrupt, bouncetime=200)# Main functiondef main(): try: configure_mcp23017() print("MCP23017 configured. Waiting for interrupts...") while True: time.sleep(1) # Keep the program running except KeyboardInterrupt: print("Exiting...") finally: GPIO.cleanup()if __name__ == "__main__": main()
Output is
Code:
sudo python3 test.py MCP23017 configured. Waiting for interrupts...Interrupt detected! Flags: 0b11111011, GPIO state: 0b11111111Interrupt detected! Flags: 0b1000, GPIO state: 0b11110111Interrupt detected! Flags: 0b1000, GPIO state: 0b11111111Interrupt detected! Flags: 0b100000, GPIO state: 0b11011111Interrupt detected! Flags: 0b100000, GPIO state: 0b11111111Interrupt detected! Flags: 0b1000, GPIO state: 0b11110111Interrupt detected! Flags: 0b1000, GPIO state: 0b11111111Interrupt detected! Flags: 0b10, GPIO state: 0b11111111Interrupt detected! Flags: 0b1000, GPIO state: 0b11110111Interrupt detected! Flags: 0b1000, GPIO state: 0b11111111
Statistics: Posted by koerli — Thu Dec 19, 2024 10:45 am