// Code based on shiftOutCode, Hello World // By : Carlyn Maw,Tom Igoe, David A. Mellis // Updated by Daniel Hirschmann to offer a way to control // cascading shift registers int latchPin = 8; //Pin connected to latch pin (ST_CP) of 74HC595 int clockPin = 12; //Pin connected to clock pin (SH_CP) of 74HC595 int dataPin = 11; //Pin connected to Data in (DS) of 74HC595 int totalLeds = 16; int ledPos = 0; int ledDirection = 1; int delayPeriod = 10; int potVal = 0; int totalSR = 3; void setup() { //set pins to output because they are addressed in the main loop pinMode(latchPin, OUTPUT); pinMode(dataPin, OUTPUT); pinMode(clockPin, OUTPUT); Serial.begin(9600); Serial.println("STARTED"); } void loop() { potVal = analogRead(0)/4; ledPos+=ledDirection; if (ledPos >= totalLeds - 1) { ledDirection = - 1; } else if (ledPos <= 0) { ledDirection = 1; } //Serial.println(ledPos); shiftToRegisters(ledPos,HIGH,2); delay(potVal); } // This method sends bits to ALL the Shift Registers: void shiftToRegisters(int whichPin, int whichState, int numberSR) { digitalWrite(latchPin, LOW); //Prepares the SR to receive data Serial.print(" pin="); //Debugging for our human brain's sake Serial.print(whichPin); Serial.print(" SRs="); Serial.print(numberSR); Serial.print(" vals = "); for (int k = numberSR-1; k >= 0; k--) //Iterate through the SR's in the chain { byte shiftRegisterByte; //Check to see if the shift register is the one with the Night Rider LED active if (whichPin - k*8 < 0) shiftRegisterByte = encodeBits(9, whichState); //This results in a byte of 0b00000000 else shiftRegisterByte = encodeBits(whichPin-k*8, whichState); //This results in a byte with the correct position active shiftOut(dataPin, clockPin, MSBFIRST, shiftRegisterByte); Serial.print(shiftRegisterByte,BIN); //More debugging for the brains Serial.print(" "); } Serial.println(); //Go to the next line of the debugging digitalWrite(latchPin, HIGH); //Tell the SR's to show us what we've just sent it! } //Function to encode a position value into a resulting position on the shift registers byte encodeBits(int pos, int val) { byte result = 0x01 << pos; return result; }