On my first arduino project, i'm trying to control eight running LEDS using a shift register and a switch button.
I have managed to light up the LEDS in the correct order, but now after i inserted the switch i have some incosistent outputs.
The LEDS must start running after the button is pressed. When the button is pressed again all LEDS must switch off. (they may end their cycle but it is not nessecary)
What i get now is sometimes all works fine.
Sometimes when i press the switch and LEDS are off, nothing happens.
When i press switch when LEDs are running, they start over from LED 1.
I think it has something to do with the delay which is needed for the LEDs to 'run', but can't seem to find the fix
int latchPin = 5;
int clockPin = 6;
int dataPin = 4;
int button = 12;
boolean state = LOW;
boolean reading;
boolean previous = LOW;
byte leds = 0;
void setup()
{
pinMode(latchPin, OUTPUT);
pinMode(dataPin, OUTPUT);
pinMode(clockPin, OUTPUT);
pinMode(button,INPUT);
}
void loop()
{
reading = digitalRead(button);
leds = 0;
updateShiftRegister();
if (reading == HIGH && previous ==LOW){
if (state == HIGH){
state = LOW;
}
else {
state = HIGH;}
}
while (state == HIGH){
for (int i = 0; i < 8; i++){
reading = digitalRead(button);
if (digitalRead(button) == HIGH){
state = LOW;
break;
}
else {
bitSet(leds, i);
updateShiftRegister();
delay(200);
}
}
leds = 0;
updateShiftRegister();
}
}
void updateShiftRegister()
{
digitalWrite(latchPin, LOW);
shiftOut(dataPin, clockPin, LSBFIRST, leds);
digitalWrite(latchPin, HIGH);
}
Any thoughts?