Skip to content

Instantly share code, notes, and snippets.

@branliu0
Created August 1, 2012 18:40
Show Gist options
  • Save branliu0/3229681 to your computer and use it in GitHub Desktop.
Save branliu0/3229681 to your computer and use it in GitHub Desktop.
Example Code for Shift Register
// Pin Definitions
// The 74HC595 uses a serial communication link which has three pins
#define PIN_DATA 2
#define PIN_CLOCK 3
#define PIN_LATCH 4
int data = 2;
int clock = 3;
int latch = 4;
void setup() {
pinMode(PIN_DATA, OUTPUT);
pinMode(PIN_CLOCK, OUTPUT);
pinMode(PIN_LATCH, OUTPUT);
}
void loop() {
for(int i = 0; i < 256; i++) {
updateLEDsLong(i);
delay(100);
}
}
/*
* updateLEDs() - sends the LED states set in ledStates to the 74HC595
* sequence
*/
void updateLEDs(int value){
digitalWrite(PIN_LATCH, LOW); // Pulls the chips latch low
//Shifts out the 8 bits to the shift register
// MSBFIRST means Most Significant Bit first
shiftOut(PIN_DATA, PIN_CLOCK, MSBFIRST, value);
digitalWrite(PIN_LATCH, HIGH); // Pulls the latch high displaying the data
}
/*
* updateLEDsLong() - sends the LED states set in ledStates to the 74HC595
* sequence. Same as updateLEDs except the shifting out is done in software
* so you can see what is happening.
*/
void updateLEDsLong(int value) {
digitalWrite(PIN_LATCH, LOW); //Pulls the chips latch low
int mask = B10000000;
for (int i = 0; i < 8; i++) {
// Send one bit of data
boolean state = ((value & mask) > 0);
digitalWrite(PIN_DATA, state ? HIGH : LOW);
// Pulse the CLOCK pin so that the shift register receives the bit of data
digitalWrite(PIN_CLOCK, HIGH);
delay(1);
digitalWrite(PIN_CLOCK, LOW);
mask >>= 1;
}
digitalWrite(latch, HIGH); //pulls the latch high shifting our data into being displayed
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment