Here is the full sketch, the discussion of how it works follows on from it.
/* Adafruit Arduino - Lesson 4. 8 LEDs and a Shift Register */ int latchPin = 5; int clockPin = 6; int dataPin = 4; byte leds = 0; void setup() { pinMode(latchPin, OUTPUT); pinMode(dataPin, OUTPUT); pinMode(clockPin, OUTPUT); } void loop() { leds = 0; updateShiftRegister(); delay(500); for (int i = 0; i < 8; i++) { bitSet(leds, i); updateShiftRegister(); delay(500); } } void updateShiftRegister() { digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, LSBFIRST, leds); digitalWrite(latchPin, HIGH); }
int latchPin = 5; int clockPin = 6; int dataPin = 4;
byte leds = 0;
void setup() { pinMode(latchPin, OUTPUT); pinMode(dataPin, OUTPUT); pinMode(clockPin, OUTPUT); }
The loop function pauses for half a second and then begins to count from 0 to 7 using the 'for' loop and the variable 'i'. Each time, it uses the Arduino function 'bitSet' to set the bit that controls that LED in the variable 'leds'. It then also calls 'updateShiftRegister' so that the leds update to reflect what is in the variable 'leds'.
There is then a half second delay before 'i' is incremented and the next LED is lit.
void loop() { leds = 0; updateShiftRegister(); delay(500); for (int i = 0; i < 8; i++) { bitSet(leds, i); updateShiftRegister(); delay(500); } }
The third parameter specifies which end of the data you want to start at. We are going to start with the right most bit, which is referred to as the 'Least Significant Bit' (LSB).
The last parameter is the actual data to be shifted into the shift register, which in this case is 'leds'.
void updateShiftRegister() { digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, LSBFIRST, leds); digitalWrite(latchPin, HIGH); }