"""Test a button on Adafruit GPIO Expander Bonnet (MCP23017 device)."""
import time

import board
import busio
import digitalio

from adafruit_mcp230xx.mcp23017 import MCP23017


class GpioButton:
    """A polled button, not debounced."""
    def __init__(self, pin):
        self.pin = pin
        self.current_value = pin.value
        self.previous_value = self.current_value

    def update(self):
        self.previous_value = self.current_value
        self.current_value = self.pin.value
        pressed = (self.previous_value == 1) and (self.current_value == 0)
        return pressed


# Initialize the I2C bus.
i2c = busio.I2C(board.SCL, board.SDA)

# Create an instance of the device. It defaults to address 0x20 on the I2C bus.
try:
    mcp = MCP23017(i2c, address=0x20)
except ValueError as err:
    print('connecting to MCP23017: {0}'.format(err))
    exit(1)

# Pin numbers on MCP23017:
# GPIOA0 --> 0
# GPIOA1 --> 1
# ..
# GPIOA7 --> 7
# GPIOB0 --> 8
# GPIOB1 --> 9
# ..
# GPIOB7 --> 15

# Get the GPIOA0 pin.
pin0 = mcp.get_pin(0)

# Set pin0 as an input with a pull-up resistor.
pin0.direction = digitalio.Direction.INPUT
pin0.pull = digitalio.Pull.UP

button = GpioButton(pin0)
count = 0

while 1:
    time.sleep(0.01)
    if button.update():
        count = count+1
        print(count)
