Hey guys,
I am a beginner of Arduino, I am now facing a problem that I want to use button to controll the numbers of LED depends on how many times I pushed the button. However, I also want to let the LED turn off every 10 sec. Which means, if I push the button 4 times, there will be 4 LEDs on, and after 10 seconds, there will be only 3 LEDs on etc. here is the code, but seems like it only works for the first LED, please give me some advices. Thank you!
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin1 = 13; // the number of the LED pin
const int ledPin2 = 12;
const int ledPin3 = 11;
const int ledPin4 = 10;
int i = 0;
// variables will change:
int buttonPushCounter = 0; // counter for the number of button presses
int buttonState = 0; // current state of the button
int lastButtonState = 0;
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
pinMode(ledPin3, OUTPUT);
pinMode(ledPin4, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
Serial.begin(9600);
}
void loop(){
// read the pushbutton input pin:
buttonState = digitalRead(buttonPin);
// compare the buttonState to its previous state
if (buttonState != lastButtonState) {
// if the state has changed, increment the counter
if (buttonState == HIGH) {
// if the current state is HIGH then the button
// wend from off to on:
buttonPushCounter++;
i++;
Serial.println("on");
Serial.print("number of button pushes: ");
Serial.println(buttonPushCounter, DEC);
}
else{
// if the current state is LOW then the button
// wend from on to off:
Serial.println("off");
i--;
delay(10000);
}
}
// save the current state as the last state,
//for next time through the loop
lastButtonState = buttonState;
if (i==0){
// turn LED off:
digitalWrite(ledPin1, LOW);
digitalWrite(ledPin2, LOW);
digitalWrite(ledPin3, LOW);
digitalWrite(ledPin4, LOW);
}
if (i==1){
digitalWrite(ledPin1, HIGH);
digitalWrite(ledPin2, LOW);
digitalWrite(ledPin3, LOW);
digitalWrite(ledPin4, LOW);
}
if (i==2){
digitalWrite(ledPin1, HIGH);
digitalWrite(ledPin2, HIGH);
digitalWrite(ledPin3, LOW);
digitalWrite(ledPin4, LOW);
}
if (i==3){
digitalWrite(ledPin1, HIGH);
digitalWrite(ledPin2, HIGH);
digitalWrite(ledPin3, HIGH);
digitalWrite(ledPin4, LOW);
}
if (i>=4){
digitalWrite(ledPin1, HIGH);
digitalWrite(ledPin2, HIGH);
digitalWrite(ledPin3, HIGH);
digitalWrite(ledPin4, HIGH);
}
}