6 Oct 2011

Knight Rider with 74HC595 8 bit shift register

Please note, the next article «Finally a threesome» includes an arduino library for the 74HC595 (not for the 74HC594) and probably obsoletes this post.





 
/**
 * Board: Pro Mini 5V
 *
 *  $Id: test_74HC595.pde 293 2011-10-06 17:30:05Z wunderlins $
 */

int SER_Pin = 8;   //pin 15 on the 75HC595
int RCLK_Pin = 9;  //pin 12 on the 75HC595
int SRCLK_Pin = 10; //pin 10 on the 75HC595

//How many of the shift registers - change this
#define number_of_74hc595s 1 

#define numOfRegisterPins number_of_74hc595s * 8
boolean registers[numOfRegisterPins];

void setup(){
  pinMode(SER_Pin, OUTPUT);
  pinMode(RCLK_Pin, OUTPUT);
  pinMode(SRCLK_Pin, OUTPUT);

  //reset all register pins
  clearRegisters();
  writeRegisters();
}               

//set all register pins to LOW
void clearRegisters() {
  for(int i = numOfRegisterPins - 1; i >=  0; i--){
     registers[i] = LOW;
  }
} 

//Set and display registers
//Only call AFTER all values are set how you would like (slow otherwise)
int direction = 1; // 1 = L2R, -1 R2L
void writeRegisters(){

  digitalWrite(RCLK_Pin, LOW);

  for(int i = numOfRegisterPins - 1; i >=  0; i--){
    digitalWrite(SRCLK_Pin, LOW);

    int val = registers[i];

    digitalWrite(SER_Pin, val);
    digitalWrite(SRCLK_Pin, HIGH);

  }
  digitalWrite(RCLK_Pin, HIGH);

}

//set an individual pin HIGH or LOW
void setRegisterPin(int index, int value){
  registers[index] = value;
}

int i = 0;
void loop(){
 
 clearRegisters();
 
  setRegisterPin(i, HIGH);
  
  writeRegisters();  //MUST BE CALLED TO DISPLAY CHANGES
  //Only call once after the values are set how you need.
  
  if (i+1 == numOfRegisterPins) {
   direction = -1;
  } else if (i == 0) {
   direction = 1;
  }
  i += direction;

  delay(100);
} 
 
Code example is borrowed from here: http://bildr.org/2011/02/74hc595/

No comments: