Try Embedded

Logic gates truth table

Two buttons feed AND, OR and XOR gates; LEDs show each output and the board prints the truth table.

Logic · Beginner

In a real product: Safety interlock (Industrial): Gates combine conditions so a machine runs only when all are safe.

Every digital chip, the microcontroller included, is built from logic gates. Here two buttons are the inputs, three gates combine them, and an LED on each output shows the result as you press.

What you'll learn

  • What AND, OR and XOR do, as a truth table
  • Pull-down resistors: why an input needs one to read a firm LOW
  • Reading signals with digitalRead() to check a circuit

How it works

Each button joins 5V to its input line while it is pressed. The 10 kΩ resistor from each line to GND (a pull-down) holds the line LOW while the button is up; without it the input would float.

The A line goes to input A of all three gates, and the B line to their input B. Each gate's output lights its LED:

ABANDORXOR
00000
01011
10011
11110

The board takes no part in the logic: it only reads the inputs and outputs on pins 2 to 6 and prints a row whenever something changes.

Try this

  • Change a gate in its settings (NAND, NOR, XNOR) and fill in its column of the table.
  • Build XOR from four NAND gates and check it gives the same column.
  • Add a D flip-flop: A to D, B to CLK. Q follows A only at the moment B is pressed: one bit of memory.

sketch.ino

// Reads two inputs (A, B) and three gate outputs (AND, OR, XOR) and prints a truth table row when they change.
const int PIN_A = 2, PIN_B = 3, PIN_AND = 4, PIN_OR = 5, PIN_XOR = 6;
int last = -1;

void setup() {
  Serial.begin(9600);
  for (int pin = 2; pin <= 6; pin++) pinMode(pin, INPUT);
  Serial.println("A B | AND OR XOR");
}

void loop() {
  int a = digitalRead(PIN_A), b = digitalRead(PIN_B);
  int g1 = digitalRead(PIN_AND), g2 = digitalRead(PIN_OR), g3 = digitalRead(PIN_XOR);
  int state = a << 4 | b << 3 | g1 << 2 | g2 << 1 | g3;
  if (state != last) {
    Serial.print(a); Serial.print(' '); Serial.print(b); Serial.print(" |  ");
    Serial.print(g1); Serial.print("   "); Serial.print(g2); Serial.print("   "); Serial.println(g3);
    last = state;
  }
  delay(20);
}

Lessons behind it