Try Embedded

Eight more pins (PCF8574)

Read four buttons and light four LEDs through a PCF8574, the I²C expander with no registers, woken by its INT pin.

Logic · Intermediate

In a real product: Industrial control panel (Industrial): An expander handles extra buttons and indicators.

The PCF8574 is the simplest I/O expander there is, and the chip on every I²C LCD backpack. It has no registers to set up: write one byte and its eight pins follow it, read one byte and you get the eight pins back.

What you'll learn

  • Quasi-bidirectional pins: how one pin is both an output and an input with no direction register
  • Sinking current: why the LEDs hang from 5 V and light when their pin goes low
  • An interrupt line that says "something changed", so the sketch reads the bus only when it must
  • I²C pull-ups on a bare chip

How it works

Writing a 1 to a pin leaves it held high only weakly (about 100 µA). A button from that pin to GND easily pulls it low, and reading the port sees it: that is how P4–P7 are inputs. Writing a 0 pulls a pin low hard, which is how P0–P3 light their LEDs: each LED runs from 5 V through a resistor into its pin, so it is on while the pin is 0. A weak high pin could not light an LED the other way round.

When an input changes, INT goes low until the port is read. The sketch watches A3 (used as a digital input) and only then reads the port, copies the button bits (P4–P7) down onto the LED bits (P0–P3), and writes it back, keeping 1s on the inputs. A pressed button reads 0, which drives its LED's pin to 0, which lights it.

The bare chip has no I²C pull-ups of its own, so two 4.7 kΩ resistors hold SDA and SCL up to 5 V.

Try this

  • Press several buttons at once (Ctrl+click keeps one pressed).
  • Write 0x00 instead of keeping the top nibble high: the inputs stop working, because the chip now pulls them low itself.
  • Tie A0 to 5 V and change ADDR to 0x21. Up to eight PCF8574s share one bus.

sketch.ino

// A PCF8574 at 0x20: four buttons on P4-P7 light four LEDs on P0-P3. INT (on A3) says when a button changed.
#include <Wire.h>

const uint8_t ADDR = 0x20;
const int INT_PIN = A3;

void writePort(uint8_t value) {
  Wire.beginTransmission(ADDR);
  Wire.write(value);
  Wire.endTransmission();
}

uint8_t readPort() {
  Wire.requestFrom(ADDR, (uint8_t)1);
  return Wire.read();
}

void setup() {
  Serial.begin(9600);
  pinMode(INT_PIN, INPUT_PULLUP);  // INT is open drain
  Wire.begin();
  writePort(0xFF);  // all LEDs off, P4-P7 ready as inputs
  Serial.println("Press the buttons");
}

void loop() {
  if (digitalRead(INT_PIN) == HIGH) return;
  uint8_t pins = readPort();
  uint8_t buttons = pins >> 4;  // 0 = pressed
  writePort(0xF0 | buttons);    // keep the inputs high; a 0 lights that LED
  Serial.print("Buttons: ");
  for (int i = 0; i < 4; i++) Serial.print(buttons & (1 << i) ? '-' : 'X');
  Serial.println();
}

Lessons behind it