I want to press my button and then the leds will start turning on and off in a sequence.
int buttonState = 0;
int tDelay = 500;
int latchPin = 11; // output register clock
int clockPin = 9; // shift register clock
int dataPin = 12; // Input
byte leds = 0;
void updateShiftRegister()
{
// setting latch pin low prepares register for input
digitalWrite(latchPin, LOW);
// writes to the register
// Will 'pulse' the Clock pin 8 times, once for each bit
shiftOut(dataPin, clockPin, MSBFIRST, leds);
digitalWrite(latchPin, HIGH);
}
void setup()
{
pinMode(2, INPUT);
pinMode(latchPin, OUTPUT);
pinMode(dataPin, OUTPUT);
pinMode(clockPin, OUTPUT);
Serial.begin(9600);
}
void loop()
{
leds = 0;
buttonState = digitalRead(2); // This function is used to
// read the digital state of a specific pin on the
// microcontroller. It's reading the state of pin 2.
if (buttonState == HIGH)
{
updateShiftRegister(); // Switch off all LEDs
delay(tDelay);
for (int i = 0; i < 6; i++)
{
leds = 0; // this is the change
bitSet(leds, i); // switches one LED on
updateShiftRegister();
delay(tDelay);
}
}
else {
updateShiftRegister();
}
}
My idea is that
- you press the button
- one led turns on and then off
- the led right next to the first one, turns on and off once the first led has turned off, and then all leds do the same
My problem: in the moment I start the simulation, the leds start turning on and off, but they completely ignore the if condition. The thing is that if I remove the push button, then the simulation does not work.
easy, just do this if (buttonState == LOW)
the buttonState will be LOW when you are pressing it, but if you are not pressing it, then it is HIGH, that is why your code is not working