Supplier photo of an assembled infinity mirror light cube illuminated on a dark background.
Supplier photo
Temu affiliate offer · Project idea

Build an infinity light cube

Listing specifies 5-volt direct current. Soldering required; battery and glue not included.

View kit on Temu

Tricky Circuit may earn a commission through these links. Product ideas have not been bench-tested by Tricky Circuit and are not verified lesson parts lists.

MCP23017 Button Panel: Interrupt Capture Is Not Debouncing

A useful control panel reports which buttons are currently pressed, even if a contact chatters or the processor is briefly busy. This build adds eight buttons to a Pico without consuming eight processor inputs. It also demonstrates a subtle distinction: the first electrical change recorded by a chip is not necessarily the final state a person intended.

Pico GP4 and GP5 connect to MCP23017 pins 13 and 12; GP6 reads INTA and GP7 resets the chip. Eight switches use GPA0–3 and GPB0–3 at 3.3 V.
Original Tricky Circuit connection diagram. Labels identify physical pins and supply rails; this is a locally reviewed design, not a measured prototype. Open full-size schematic

Choose the exact expander and input pins

An input/output expander adds digital pins that a processor accesses through numbered registers, small storage locations controlling hardware. I²C means Inter-Integrated Circuit: here, a short two-wire link with serial data (SDA) and serial clock (SCL). Our exact part is Microchip MCP23017-E/SP, in SPDIP-28. A similarly named MCP23S17 uses a different serial interface and cannot run this wiring or program.

Use GPA0–3 and GPB0–3. The current DS20001952E identifies GPA7 and GPB7 as output-only on MCP23017. We explicitly make those unused pins outputs, rather than relying on an older library’s “16 input” example. Operate the whole circuit at 3.3 V; this is a normal supply condition, not an experiment near an absolute maximum. Never pull a Pico signal to 5 V.

Parts and equipment

  • One original Raspberry Pi Pico RP2040 with MicroPython 1.26.0, USB cable and breadboard.
  • Microchip MCP23017-E/SP: 28-pin skinny plastic dual in-line package (SPDIP); eight normally open pushbuttons.
  • Two 4.7 kΩ bus pullups, one 10 kΩ INTA pullup, one 10 kΩ RESET pullup, 100 nF ceramic supply bypass; short wires.

Every connection

Pin or partConnection and purpose
SupplyPico 3V3 OUT physical 36 → U1 VDD pin 9; Pico GND 38 → VSS pin 10. 100 nF directly across 9/10.
BusGP4 physical 6 → SDA pin 13; GP5 physical 7 → SCL pin 12. Each line has its own 4.7 kΩ resistor to 3.3 V.
Address and resetA0/A1/A2 pins 15/16/17 to ground: 7-bit address 0x20. RESET pin 18 → GP7 physical 10, plus 10 kΩ to 3.3 V.
InterruptINTA pin 20 → GP6 physical 9, with 10 kΩ to 3.3 V. INTB pin 19 left unconnected; the two ports are mirrored internally.
Buttons 1–4GPA0/GPA1/GPA2/GPA3 pins 21/22/23/24: each to one separate button, other side to ground. Internal pullups enabled.
Buttons 5–8GPB0/GPB1/GPB2/GPB3 pins 1/2/3/4: same arrangement.
Unused pinsGPB4–7 pins 5–8 and GPA4–7 pins 25–28 configured as low outputs, externally unconnected. NC pins 11 and 14 unconnected.

What the supporting components do

I²C devices release a wire to send a high level; pullup resistors bring the released line to the supply. A low line sinks approximately 3.3/4700 = 0.70 mA through its pullup. The interrupt has a separate 10 kΩ pullup, about 0.33 mA when asserted. Do not replace these resistors with direct supply wires. The 100 nF capacitor supplies brief local demand and belongs close to the chip, not at the far end of the breadboard.

Button pullups are internal and comparatively weak. Keep their wires short for this experiment. A released button reads one; a pressed button connects to ground and reads zero. The program inverts only the four used bits in each port and packs them into one eight-bit mask. Button 1 corresponds to 0x01 and button 8 to 0x80; together they give 0x81.

Reset, configure, capture, reconcile

The code first drives hardware RESET low for 10 ms, then releases it high. This establishes the register bank layout before writes: stopping and restarting an interpreter does not necessarily reset an external chip. Registers 0x00/0x01 make the lower four bits inputs; the upper bits are outputs. Output latches are set low before direction changes. Address straps never float.

The configuration value 0x44 mirrors both port interrupts and selects an open-drain interrupt output. Open-drain means the output can pull low or release, so its external resistor defines high. An interrupt-on-change records a snapshot in INTCAP. Reading the captured registers acknowledges the event; reading current GPIO registers can also clear it. Consequently the two reads have different purposes: captured data helps explain what first happened, while periodic current reads establish what is true now.

There is no queue containing every transition. Several changes can coalesce while an interrupt is pending. This design deliberately prints captured masks as diagnostic history, never as a count of valid button presses. Every 5 ms it also reads both current ports. A candidate mask must persist for at least 30 ms before it becomes a reported stable state. This whole-mask debounce is simple, but one chattering button can delay acceptance of another; independent per-button filters are a useful extension.

Complete program

"""Pico / MicroPython 1.26.0. Run from a clean power-on/reset state."""
def unpack(a, b):
    return ((~a) & 15) | (((~b) & 15) << 4)

class Debounce:
    def __init__(self):
        self.candidate = self.stable = None
        self.age = 0
    def sample(self, value, elapsed_ms):
        if value != self.candidate:
            self.candidate, self.age = value, 0
        else:
            self.age += elapsed_ms
        if self.age >= 30 and value != self.stable:
            self.stable = value
            return value
        return None

class Panel:
    def __init__(self, bus):
        self.bus = bus
        self.put(0x0a, 0x44)  # BANK=0, MIRROR=1, ODR=1, sequential enabled
        self.put(0x04, 0); self.put(0x05, 0)  # disable interrupts during setup
        self.put(0x14, 0); self.put(0x15, 0)  # output latches low
        self.put(0x00, 0x0f); self.put(0x01, 0x0f)  # A0..3/B0..3 inputs
        self.put(0x02, 0); self.put(0x03, 0)  # no polarity inversion
        self.put(0x0c, 0x0f); self.put(0x0d, 0x0f)  # weak internal pullups
        self.put(0x08, 0); self.put(0x09, 0)  # compare with previous sample
        self.read(0x12)  # clear pending state for both ports
        self.put(0x04, 0x0f); self.put(0x05, 0x0f)
    def put(self, reg, value):
        self.bus.writeto_mem(0x20, reg, bytes([value]))
    def read(self, reg):
        data = self.bus.readfrom_mem(0x20, reg, 2)
        if len(data) != 2:
            raise OSError('short register read')
        return unpack(data[0], data[1])
    def captured(self):
        return self.read(0x10)  # INTCAPA/B; read clears captured interrupts
    def current(self):
        return self.read(0x12)  # GPIOA/B; also acknowledges interrupts

def main():
    from machine import Pin, SoftI2C
    from time import sleep_ms, ticks_ms, ticks_diff
    bus = SoftI2C(sda=Pin(4), scl=Pin(5), freq=100000, timeout=20000)
    irq = Pin(6, Pin.IN)
    reset = Pin(7, Pin.OUT, value=0)
    sleep_ms(10); reset.value(1); sleep_ms(10)
    try:
        panel = Panel(bus)
    except OSError as exc:
        print('SETUP ERROR; inspect wiring, then restart:', exc)
        return
    filt = Debounce(); last = ticks_ms()
    while True:
        try:
            if not irq.value():
                print('captured (not debounced):', panel.captured())
            now = ticks_ms(); elapsed = ticks_diff(now, last); last = now
            state = filt.sample(panel.current(), min(elapsed, 10))
            if state is not None:
                print('stable pressed mask:', hex(state))
        except OSError as exc:
            print('BUS ERROR; state unknown; restart after repair:', exc)
            return
        sleep_ms(5)
if __name__ == '__main__':
    main()

Run the panel

  1. With power disconnected, orient the chip notch and check the pin table. Program the original Pico with MicroPython 1.26.0 and open its serial console. Save the complete listing as main.py to run at startup.
  2. Start with all buttons released. Expect stable mask 0x0. Press button 1 for half a second: expect 0x1, then 0x0 after release. The captured output may contain extra transitions.
  3. Press buttons 1 and 8 together. The settled mask should become 0x81. Try a very brief tap: rejection by the 30 ms filter is an intended limitation, not evidence of a missing interrupt.
  4. Temporarily disconnect only the INTA-to-GP6 wire, leaving its pullup at the Pico input. Periodic current reads should still report settled buttons. Restore the wire with power off.
  5. Power off before testing a disconnected SDA wire. On restart, a setup or bus error should be explicit; it must not be presented as “all buttons released.” Repair wiring and restart the program.

Boundaries and revision checks

The historical Rev. A erratum DS80252A describes false acknowledgements in A0 and earlier silicon, corrected in A1. Check the actual purchased device date/revision before sharing this bus with other devices. This old issue is separate from the current GPA7/GPB7 restriction. A lesson’s chip name does not establish the revision of a part in your drawer.

This panel accepts human-scale presses, not encoder pulses or safety interlocks. A bus exception ends the program with state unknown; it does not silently create a fresh empty panel. Restart after repairing the cause. Local tests check masks, configuration writes and debounce behavior; this circuit has not been physically tested. Record contact timing and observed errors during your build.

Challenge: can the captured mask replace periodic reads?

No. It records a historical event and multiple changes can occur before it is serviced. Periodic reads reconcile the final state, while a real event counter would require different hardware and timing guarantees.

Sources and related lessons

Continue with why a voltage divider drops under load, measuring current through a resistor with a voltmeter, and the interactive circuit lessons.

📡Broadcast the signal — amplify the connection.

Leave a Reply

Temu affiliate offers

Find your next electronics project

Explore these do-it-yourself project kits. Check the selected option, included parts and instructions on each offer.

Tricky Circuit may earn a commission if you buy through these Temu affiliate links. These are product ideas; they have not been bench-tested by Tricky Circuit and are not verified lesson parts lists.

Supplier photo of a breadboard, jumper wires and assorted electronic components in a plastic storage case.

Supplier product photo

Try breadboard experiments

Breadboard, wires and assorted parts. Arduino controller board not included.

View kit on Temu

Supplier photo of an assembled blue surface-mount soldering practice board with a circular ring of small lights.

Supplier product photo

Solder a chasing-light board

Surface-mount soldering practice. Battery and battery holder not included.

View kit on Temu

Supplier photo of an assembled two-wheeled line-following car with a blue circuit board, two motors and an empty battery holder.

Supplier product photo

Build a line-following car

Soldering and assembly required. Check battery and track requirements before buying.

View kit on Temu