Wednesday, 2 July 2014

Using Shift Registers (74HC595)

This is one of the trickiest but most useful arduino project. Arduino pins are limited. When running out of pins, this method can be used to expand the outputs. Using 74HC595 IC,  I am able to control 8 LEDs using 3 pins.


About 74HC595:

74HC595 is a parrallel serial shift register. It has 16 pins with 8 memory locations, output enable(active low), Storage clock pin(latch pin), memory reset(active low), Shift Clock pin(clock pin), Serial Data pin, Vcc and ground.
The Pinnig Diagram is as shown below:


BreadBoard Layout:
To enable the output, pin 13 is connected to ground. Not to clear the memory, 10th pin is connected to Vcc. Pins 1-7, 15 are connected to LEDs via resistors. Pins 11 , 12 and 14 are connected to the arduino . 



Building virtual circuits : http://fritzing.org

New terms in code:
  • byte : it is datatype that stores value of 8 bits
  • bitSet(x, n): assigns '1' to nth bit of variable x
  • bitClear(x, n):assigns '0' to nth bit of variable x 
  • shiftOut() : (This thing confused me a lot!!) It shifts out a byte of data either starting from leftmost   bit(MSBFIRST) or rightmost bit(LSBFIRST) 
                            Syntax: shiftOut (pin1,  pin2, order,  variable)
        • <int> pin1: data pin to which bit in the byte variable is to be shifted
        • <int> pin2: clock pin to toggle
        • order: MSBFIRST or LSBFIRST
        • <byte> variable: bits which are to be shifted to the data pin

Code:



int DS_pin=8;
int SH_pin=10;
int ST_pin=9;

void setup()
{
  pinMode(DS_pin,OUTPUT);
  pinMode(ST_pin,OUTPUT);
  pinMode(SH_pin,OUTPUT);
}

byte registers;

void loop()
  registers=0;
  writereg();
  for(int i=0; i<8; i++)
  {
   bitSet(registers, i);
    writereg();
    delay(500);
  }
   for(int i=7; i>=0; i--)
  {
   bitClear(registers, i);
    writereg();
    delay(500);
  }

}

void writereg()
{
   digitalWrite(ST_pin,LOW);
  shiftOut(DS_pin, SH_pin, LSBFIRST, registers);
  digitalWrite(ST_pin, HIGH);
}

Explanation to the code:

The variable "registers" is assigned the datatype byte and is intialized to "00000000" within the loop. In writereg()  function, a transition from low state to high state of Latch pin(ST_pin)  is created in which the data is shifted. Shifting out the value of "registers" to the data pin (DS_pin) bit by bit is done for every clock transition (SH_pin) while this is latched onto the register for every transition in latch pin. 
Refer the function table in the 74HC595 Datasheet.
There are two for loops within the setup(), one for glowing the LEDs and other for turning it off.
In the first for loop, bitSet is used for turning on an LED and shift register is updated by writereg() .The second for loop is just the reverse of the first one. It uses bitClear instead of bitSet for switching off the LEDs.

No comments:

Post a Comment