I am not familiar with using shift registers. I am using this code to control 8 leds.
int tDelay = 500;
int latchPin = 11; // (11) ST_CP [RCK] on 74HC595
int clockPin = 9; // (9) SH_CP [SCK] on 74HC595
int dataPin = 12; // (12) DS [S1] on 74HC595
byte leds = 0;
// this first function to turn them off, from right to left (least significant)
void updateShiftRegister()
{
digitalWrite(latchPin, LOW);
shiftOut(dataPin, clockPin, LSBFIRST, leds); //LSBFIRST starts from the least significant Byte, that corresponds to 8th pinout
digitalWrite(latchPin, HIGH);
}
// this second function is to turn them off
void updateShiftRegister2()
{
digitalWrite(latchPin, HIGH);
shiftOut(dataPin, clockPin, LSBFIRST, leds); //if we start with MSBFIRST in this function, then it would start from the most significant, that is the 1st pinout.
digitalWrite(latchPin, LOW);
}
void setup()
{
pinMode(latchPin, OUTPUT);
pinMode(dataPin, OUTPUT);
pinMode(clockPin, OUTPUT);
Serial.begin(9600);
}
void loop()
{
leds = 0;
updateShiftRegister();
for (int i = 0; i < 8; i++)
{
delay(tDelay);
bitSet(leds, i); //bitset sets the byte of each led to on
updateShiftRegister();
}
}
It turns on the led's from right to left. The code is working well. But I want to individually control an led, to control led 1 or 2 or any led of this project, how can I do so ! I couldn't figure it out.
My intention was, to control any specific output of shift registers. As there, 8 led's are connected, How I could control any specific led, if I want to.
And I found the simplest way to do so:
You don't need to call updateShiftRegister before modifying 'leds'. And, you could do it like this :
void updateShiftRegister( const uint8_t value )
{
digitalWrite(latchPin, LOW);
shiftOut(dataPin, clockPin, LSBFIRST, value );
digitalWrite(latchPin, HIGH);
}
void loop()
{
// this is equivalent to your code
updateShiftRegister( 0b00000001 ); // led 0 on, other leds off
delay(2500);
updateShiftRegister( 0b00000100 ); // led 2 on, other leds off
delay(1000);
updateShiftRegister( 0b00010100 ); // leds 2 and 4 on, other leds off
delay(200);
updateShiftRegister( 0b00010010 ); // leds 1 and 4 on, other leds off
delay(500);
updateShiftRegister( 0b00010000 ); // led 4 on, other leds off
delay(4000);
updateShiftRegister( 0b00001000 ); // led 3 on, other leds off
delay(1000);
updateShiftRegister( 0 ); // all leds off
delay(5000);
}