I'm currently taking a course for Computer Programming using the Arduino IDE and this current objective has gotten me confused on how to program. The objective is to use the Arduino with 4 LEDs and a button as a switch. When the button is pressed once, one LED turns on. When the button is pressed again, the next LED turns on, and ect. until all are lit. The 5th button press should turn them all off. Currently my setup is both the Arduino and the breadboard, with leads coming from the pins to 220 ohm resistors, to the positives on the LEDs and then grounded on the negatives. I believe using and 'if' statement with 'case' statements would be best but I cannot figure out how to use it as a switch and not just a momentary switch when the button changes state. I know this code is not complete in all that I have to do, I just need some guidance.
int ledPin1 = 12;
int ledPin2 = 11;
int ledPin3 = 10;
int ledPin4 = 9;
int buttonPress1 = 2;
int countBP = 0;
void setup()
{
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
pinMode(ledPin3, OUTPUT);
pinMode (ledPin4, OUTPUT);
pinMode(buttonPress1, INPUT_PULLUP);
}
void loop()
{
digitalWrite(ledPin1, LOW);
digitalWrite(ledPin2, LOW);
digitalWrite(ledPin3, LOW);
digitalWrite(ledPin4, LOW);
countBP = digitalRead(buttonPress1);
while (countBP != 0)
{
switch (countBP)
{
if (countBP == 0)
{
case 1:
digitalWrite(ledPin1, HIGH);
digitalWrite(ledPin2, LOW);
digitalWrite(ledPin3, LOW);
digitalWrite(ledPin4, LOW);
countBP = countBP + digitalRead(buttonPress1);
break;
}
if (countBP == 1)
{
case 2:
digitalWrite(ledPin1, HIGH);
digitalWrite(ledPin2, HIGH);
digitalWrite(ledPin3, LOW);
digitalWrite(ledPin4, LOW);
countBP = countBP + digitalRead(buttonPress1);
break;
}
if (countBP == 2)
{
case 3:
digitalWrite(ledPin1, HIGH);
digitalWrite(ledPin2, HIGH);
digitalWrite(ledPin3, HIGH);
digitalWrite(ledPin4, LOW);
countBP = countBP + digitalRead(buttonPress1);
break;
}
if (countBP == 3){
case 4:
digitalWrite(ledPin1, HIGH);
digitalWrite(ledPin2, HIGH);
digitalWrite(ledPin3, HIGH);
digitalWrite(ledPin4, HIGH);
countBP = countBP + digitalRead(buttonPress1);
break;
}
default:
digitalWrite(ledPin1, LOW);
digitalWrite(ledPin2, LOW);
digitalWrite(ledPin3, LOW);
digitalWrite(ledPin4, LOW);
countBP = 0;
break;
}
}
}
Uploaded to the Arduino and all the LEDs light up. However, when the button is pressed and held down, but it is entirely random when they shut off and when one turns on, ect. Sometimes some only dim and not shut off or turn on completely. Then when the button is released, they all light up again.
I might need a 'previousButtonState' possibly so it counts the change in state and moves forward? Does this setup need to be 'debounced'? I've been reading a bunch but I'm not sure in how to implement it. Thank you!