Reputation: 1
I want to make a 5 seconds timer in arduino, to be more detailed, I have a RGB led and i want to light up a color for the number of times I press a button (I have a push button too), like, in those 5 seconds the led must remain unlighted, in the same 5 seconds if I press the button once, after the timer ends (5 seconds) the led will turn red, if I press the button two times the led turns blue or whatever.
const int buttonPin = 2; // the number of the pushbutton pin
const int ledbPin = 13; // the number of the LED pin
const int ledgPin = 12; // the number of the LED pin
const int ledrPin = 11; // the number of the LED pin
int count = 0; // Count the button presses
unsigned long currentTime;
unsigned long loopTime;
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
void setup() {
// initialize the LED pin as an output:
pinMode(ledrPin, OUTPUT);
pinMode(ledgPin, OUTPUT);
pinMode(ledbPin, OUTPUT);
currentTime = millis();
loopTime = currentTime;
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}
void loop(){
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
count++; // add 1 to the count
if (count >= 1) {
currentTime = millis();
if(currentTime >= (loopTime + 5000)){
if (count == 1) {
digitalWrite(ledrPin, HIGH);
}
if (count == 2) {
digitalWrite(ledgPin, HIGH);
}
if (count == 3) {
digitalWrite(ledbPin, HIGH);
}
}
}
}
}
This is what I wrote so far:
After the timer ends, if I press the button, all the leds are turning on, making white color.
Upvotes: 0
Views: 3901
Reputation: 373
It's because you are making an if statement in a loop. The loop is too fast. While you are pressing and releasing the button, it already does the loop multiple times. In those multiple times, your Count is still getting higher and higher. I would add a millis to the If statement of the button. I just made an example here. You can do it your way.
void loop(){
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH && currentTime == 500 (didnt look which one your timer is)) {
count++; // add 1 to the count
if (count >= 1) {
currentTime = millis();
if(currentTime >= (loopTime + 5000)){
if (count == 1) {
digitalWrite(ledrPin, HIGH);
}
if (count == 2) {
digitalWrite(ledgPin, HIGH);
}
if (count == 3) {
digitalWrite(ledbPin, HIGH);
}
}
}
}
}
Upvotes: 1