In my project, I am trying to create a timer display with LEDs base on how long a button was pressed and hold.
There are 8 LED lights in total, when the toggle button was pressed, 1st LED lights up; keep holding/ pressing the button, the 2nd LED lights up after 1sec, the 3rd LED lights up after 2sec and so on. So 7s after the button was pressed and hold, all 8 LEDs shall light up. When the button was released at anytime, all LEDs would be off.
Something is wrong with my code which the timer seems not working (saving the time when the button was pressed) and calculate the time difference ("current time" - "time when button pressed") in order to lights up the LED.
My codes:
int current;
long millis_held;
long prev_secs_held;
unsigned long firstTime;
byte previous = LOW;
const int buttonPin = 13;
void setup() {
pinMode(buttonPin, INPUT);
pinMode(2,OUTPUT) ;
pinMode(3,OUTPUT) ;
pinMode(4,OUTPUT) ;
}
void loop() {
current = digitalRead(buttonPin);
if (current == HIGH && previous == LOW) {
firstTime = millis();
digitalWrite(2, HIGH);
millis_held = (millis() - firstTime);
if (millis_held >= 1000 && firstTime <2000){
digitalWrite(3, HIGH);
}
if (millis_held >= 2000){
digitalWrite(4, HIGH);
}
}
else {
digitalWrite(2, LOW);
digitalWrite(3, LOW);
digitalWrite(4, LOW);
}
}
Hope you guys can help, thanks a lot.
if I waited too long before initiating the 1st button press, same thing happens with all LEDs light up together
... that indicates that you are not waiting for the button to be pressed before starting the timer