mcp230xx_event_detect_interrupt.py
1 # SPDX-FileCopyrightText: 2017 Tony DiCola for Adafruit Industries 2 # 3 # SPDX-License-Identifier: MIT 4 5 from time import sleep 6 7 import board 8 import busio 9 from digitalio import Direction, Pull 10 from RPi import GPIO 11 from adafruit_mcp230xx.mcp23017 import MCP23017 12 13 # Initialize the I2C bus: 14 i2c = busio.I2C(board.SCL, board.SDA) 15 16 # Initialize the MCP23017 chip on the bonnet 17 mcp = MCP23017(i2c) 18 19 # Optionally change the address of the device if you set any of the A0, A1, A2 20 # pins. Specify the new address with a keyword parameter: 21 # mcp = MCP23017(i2c, address=0x21) # MCP23017 w/ A0 set 22 23 # Make a list of all the pins (a.k.a 0-16) 24 pins = [] 25 for pin in range(0, 16): 26 pins.append(mcp.get_pin(pin)) 27 28 # Set all the pins to input 29 for pin in pins: 30 pin.direction = Direction.INPUT 31 pin.pull = Pull.UP 32 33 # Set up to check all the port B pins (pins 8-15) w/interrupts! 34 mcp.interrupt_enable = 0xFFFF # Enable Interrupts in all pins 35 # If intcon is set to 0's we will get interrupts on 36 # both button presses and button releases 37 mcp.interrupt_configuration = 0x0000 # interrupt on any change 38 mcp.io_control = 0x44 # Interrupt as open drain and mirrored 39 mcp.clear_ints() # Interrupts need to be cleared initially 40 41 # Or, we can ask to be notified CONTINUOUSLY if a pin goes LOW (button press) 42 # we won't get an IRQ pulse when the pin is HIGH! 43 # mcp.interrupt_configuration = 0xFFFF # notify pin value 44 # mcp.default_value = 0xFFFF # default value is 'high' so notify whenever 'low' 45 46 47 def print_interrupt(port): 48 """Callback function to be called when an Interrupt occurs.""" 49 for pin_flag in mcp.int_flag: 50 print("Interrupt connected to Pin: {}".format(port)) 51 print("Pin number: {} changed to: {}".format(pin_flag, pins[pin_flag].value)) 52 mcp.clear_ints() 53 54 55 # connect either interrupt pin to the Raspberry pi's pin 17. 56 # They were previously configured as mirrored. 57 GPIO.setmode(GPIO.BCM) 58 interrupt = 17 59 GPIO.setup(interrupt, GPIO.IN, GPIO.PUD_UP) # Set up Pi's pin as input, pull up 60 61 # The add_event_detect fuction will call our print_interrupt callback function 62 # every time an interrupt gets triggered. 63 GPIO.add_event_detect(interrupt, GPIO.FALLING, callback=print_interrupt, bouncetime=10) 64 65 # The following lines are so the program runs for at least 60 seconds, 66 # during that time it will detect any pin interrupt and print out the pin number 67 # that changed state and its current state. 68 # The program can be terminated using Ctrl+C. It doesn't matter how it 69 # terminates it will always run GPIO.cleanup(). 70 try: 71 print("When button is pressed you'll see a message") 72 sleep(60) # You could run your main while loop here. 73 print("Time's up. Finished!") 74 finally: 75 GPIO.cleanup()