Try Embedded

16 more pins with an I/O expander (MCP23017)

Drive eight LEDs and read a button through an MCP23017 on I²C, with an interrupt instead of polling.

Logic · Intermediate

In a real product: Elevator control panel (Industrial): An expander reads many buttons and lights many indicators.

Out of pins? An MCP23017 adds sixteen digital pins over the two I²C wires, and eight of them can share one bus. Each pin is an input or an output, with an optional pull-up, as on the board itself.

What you'll learn

  • Setting pin modes and levels on a remote chip through its registers
  • Reading a button through the expander's pull-up
  • Using the expander's interrupt output so the board does not have to poll

How it works

Port A (pins 0–7 in the library) drives the bar graph's LEDs; port B's first pin (8) reads a button with the chip's own pull-up. The library writes the chip's IODIR, GPPU and OLAT registers over I²C.

setupInterruptPin(8, CHANGE) makes the chip pull INTB LOW when the button changes. The board only reads the expander when its pin 2 sees that LOW. Reading the port clears the interrupt. RESET is tied to 5V and A0–A2 to GND, which gives address 0x20.

The two 4.7 kΩ resistors from SDA and SCL to 5V are the bus's pull-ups. I²C devices only ever pull the lines low, so something must pull them high again; a breakout module carries its own pull-ups, but this bare chip has none.

Try this

  • Press the button while it runs: the light moves one step along the bar.
  • Hold the button and watch INTB: it stays LOW until the sketch reads the port.
  • Use port B's other pins for seven more buttons and find which one changed with getLastInterruptPin().

sketch.ino

// An MCP23017 at 0x20: LEDs on GPA0-GPA7, a button on GPB0 (pin 8) with its pull-up, INTB to pin 2.
#include <Adafruit_MCP23X17.h>

Adafruit_MCP23X17 mcp;
int position = 0;

void show() {
  for (int i = 0; i < 8; i++) mcp.digitalWrite(i, i == position);
}

void setup() {
  Serial.begin(9600);
  pinMode(2, INPUT);
  if (!mcp.begin_I2C(0x20)) {
    Serial.println("No MCP23017 at 0x20");
    while (true) {}
  }
  for (int i = 0; i < 8; i++) mcp.pinMode(i, OUTPUT);
  mcp.pinMode(8, INPUT_PULLUP);
  mcp.setupInterrupts(false, false, LOW);
  mcp.setupInterruptPin(8, CHANGE);
  mcp.clearInterrupts();
  show();
}

void loop() {
  if (digitalRead(2) == HIGH) return;          // INTB idle: nothing changed
  bool pressed = mcp.digitalRead(8) == LOW;    // reading the port clears the interrupt
  if (pressed) {
    position = (position + 1) % 8;
    show();
    Serial.print("Position ");
    Serial.println(position);
  }
  delay(20);                                    // let the contact bounce settle
  mcp.clearInterrupts();
}

Lessons behind it