Shift Register Demo

An online demo on how a shift register works.

How to use a shift register

Here's a quick demo I built on how a shift register works for a video. I can't promise it'll be completely accurate, but it'll give you an idea of how it works.

Shift Register Demo

Q4
0
Q3
0
Q2
0
Q1
0
Q0
0

How to Use

  1. Set the Data pin to 1 (ON) or 0 (OFF) using the switch
  2. Click the Clock button to shift to the next output
  3. Toggle the Latch switch to ON to update all the outputs
  4. Toggle the Latch switch to OFF before the next clock pulse, to set your new data

Try This Demo Pattern:

  1. Set Data = ON, Click Clock (shifts in a 1)
  2. Set Data = OFF, Click Clock 4 times (shifts in zeros)
  3. Turn Latch ON to see the result
  4. Turn Latch OFF to prepare for next sequence

Controlling a Shift Register with a Raspberry Pi

The demo above shows how a shift register works in the browser, but how would we control one in the real world with Python? Here's a simple example using a Raspberry Pi and the GPIO library.

First, let's set up our pins:

import RPi.GPIO as GPIO
import time

# Set up the GPIO pins
GPIO.setmode(GPIO.BCM)

# Define pins
DATA_PIN = 17   # Serial data input
CLOCK_PIN = 27  # Clock input
LATCH_PIN = 22  # Register clock input

# Set up pins as outputs
GPIO.setup(DATA_PIN, GPIO.OUT)
GPIO.setup(CLOCK_PIN, GPIO.OUT) 
GPIO.setup(LATCH_PIN, GPIO.OUT)

Now we can write a simple function to shift out data:

def shift_out(data_bit):
    # Set data pin
    GPIO.output(DATA_PIN, data_bit)

    # Pulse clock pin
    GPIO.output(CLOCK_PIN, GPIO.HIGH)
    time.sleep(0.001)  # Small delay
    GPIO.output(CLOCK_PIN, GPIO.LOW)

And here's how we would send a full byte of data:

def send_byte(byte):
    # Shift out each bit
    for i in range(8):
        bit = (byte >> i) & 1  # Get each bit starting from LSB
        shift_out(bit)

    # Pulse latch pin to update outputs
    GPIO.output(LATCH_PIN, GPIO.HIGH)
    time.sleep(0.001)
    GPIO.output(LATCH_PIN, GPIO.LOW)

# Example: Light up alternating LEDs
send_byte(0b10101010)  # Binary pattern

This code follows the same principles as our browser demo - we're controlling the data, clock, and latch pins to shift in bits one at a time. The main differences are:

  1. We're using actual GPIO pins instead of virtual ones
  2. We need small delays to ensure the shift register has time to respond
  3. We can send a full byte at once rather than bit-by-bit

Remember to clean up your GPIO when you're done:

# Clean up GPIO on exit
GPIO.cleanup()

This is a basic example - in practice, you might want to add error handling and possibly use hardware SPI for more reliable communication. But this demonstrates the core concepts of how shift registers work in real hardware!