by

Using 74HC595 Shift Registers with Arduino

Using a shift register like the 74HC595 you can convert a serial signal to a parallel output. This is incredibly helpful if you need more digital outputs then the 14 that the ATmega328 on the Arduino Uno provides. The Arduino IDE includes a shiftOut() function that can be used to control an 8-bit shift register like the 74HC595 but I usually like to have complete control over my code so I understand what is going on. For more about how the 74HC595 works see this post then take a look at the code below, which makes it work. The comments in the code should be helpful too.

const int dataPin = 6; // can be any digital pin on the Arduino
const int clockPin = 7; // can be any digital pin on the Arduino
const int latchPin = 8; // can be any digital pin on the Arduino
byte data = B00100101; // the byte you wish to send to the shift 
// register

void setup(void) {
  
  pinMode(dataPin,OUTPUT);
  pinMode(clockPin,OUTPUT);
  pinMode(latchPin,OUTPUT);
  digitalWrite(clockPin,LOW);

}

void loop(void) {
  digitalWrite(latchPin,LOW); // set low to prevent changes from 
  // updating the output register.
  myShiftOut(data,clockPin,dataPin); // send 
  digitalWrite(latchPin,HIGH);
}

void myShiftOut(byte data, int clockPin, int dataPin) {
 // The 74HC595 shift register stores incoming bits as the least 
 // significant bit in the storage register. The most significant 
 // bit gets pushed out. More than one 74HC595 can be daisy chained 
 // together by connecting the Q7' pin (pin 9) of the first shift 
 // register to the data pin (pin 14) of the second. When more
 // than one 74HC595 are used in series they all share a clock 
 // (pin 11) and latch (pin 12) with the microcontroller.
 // Basic opperation: On the rising edge of the clock, whatever is 
 // on the data pin gets stored in the storage register. Setting 
 // the latch pin high puts whatever is in the storage register in 
 // the output register.
 
 boolean pinState 
 digitalWrite(clockPin, LOW); // set these low to start
 digitalWrite(dataPin, LOW); 
 
 for (int ii=0; ii<7; ii++) {
   if (data & (B10000000>>ii)) { // this is a bit mask using 
   // a bitwise and operator. In this form, the most significant 
   // bit is sent first.
     pinState = HIGH;
   }
   else {
     pinState = LOW;
   }
   digitalWrite(dataPin, pinState);
   digitalWrite(clockPin, HIGH);
   digitalWrite(clockPin, LOW);
 }
}

Leave a Reply

Your email address will not be published.