Thursday, March 4, 2010

Shift Registers

Lots of projects on sites like Make and Instructables make use of shift registers but what are they exactly? The most basic way to explain what they do is to say that they expand the number of digital pins available to use (with some downsides). A more complex way to explain them is to call them a cascade of flip-flops. What this means is that with only 2 data pins, you can control 8 (or more with different chips) digital outputs (but not inputs). A common chip used with Arduinos are 74HC164 (I got mine from Jaycar for $3.50 74HC164 8-bit Serial in/out Shift Register IC) and here is a project that gives a basic run down of the chip and some simple projects to use them in http://www.instructables.com/id/The-74HC164-Shift-Register-and-your-Arduino/. The below code is adapted from project two from the instructables link to emulate a program I wrote earlier ("snake" around a 7 segment display):

#define data 2
#define clock 3

byte zero = B11100000;
byte one = B01110000;
byte two = B10110000;
byte three = B10011000;
byte four = B10001100;
byte five = B00001110;
byte six = B10000110;
byte seven = B11000010;//these are variables that specify which pins should be turned on

void setup()
{
pinMode(clock, OUTPUT);
pinMode(data , OUTPUT);

void loop()
{
shiftOut(data, clock, LSBFIRST, zero);
delay(100);
shiftOut(data, clock, LSBFIRST, one);
delay(100);
shiftOut(data, clock, LSBFIRST, two);
delay(100);
shiftOut(data, clock, LSBFIRST, three);
delay(100);
shiftOut(data, clock, LSBFIRST, four);
delay(100);
shiftOut(data, clock, LSBFIRST, five);
delay(100);
shiftOut(data, clock, LSBFIRST, six);
delay(100);
shiftOut(data, clock, LSBFIRST, seven);
delay(100);
}

shiftOut is a specialised command for shift registers. the first two values specify the data pin (the pin which sends a high/low pattern) and the clock pin (this breaks up the individual values in one variable by cycling high/low to specify the end of a value). LSBFIRST is short for Last Significant Bit First and is used to specify in which order the byte pattern is loaded and then the byte pattern for the shift register to use (B11110000 for example will turn pins 1,2,3 and 4 on high from the shift register and 5,6,7 and 8 on low).

No comments:

Post a Comment