hello i have a problem whit programming my code . i try to create a while loop that when i push a button my led will blink 3 times . the problem is when i push the button it blinks 4 times and can reset to do it over again
int i = 0;
void setup() {
pinMode(4, OUTPUT);
pinMode(8, INPUT_PULLUP);
Serial.begin(9600);
}
void loop() {
if (digitalRead(8) == LOW)
{
while (i <= 3) {
digitalWrite(4, HIGH);
delay(1000);
digitalWrite(4, LOW);
delay(1000);
i++;
}
}
}
Walk through the code, line by line. Start with i=0 and count the number of blinks you'll see until the condition you have within the while(...) is false.
i have a question now i try to make when i push the button 3 times the led goes on and when i push the button 3 times it goes off i need to make it in a while loop . i try to make a whil pushbutton is pushed 3 times led goes on put it dont work why
int i = 3;
void setup() {
pinMode(4, OUTPUT);
pinMode(4, INPUT_PULLUP);
Serial.begin(9600);
}
void loop() {
if(digitalRead(4) == i);
while (i==3)
{
digitalWrite(4, HIGH);
}
}
Don't use while, especially in loop(). It just invites problems.
Just count the button presses then toggle the LED when the count ==2
[b]Pseudo code:[/b]
int i=0;
loop:{
if (buttonPressed()) i=+1;
if (i>=2) {
toggle LED;
i=0;
}
}
Depending on the quality of the button, this may appear to not work. You have no debounce, so pressing the button may register as two, or ten button presses. This is why I show buttonPress() as a function where you can check and debounce button presses. Personally, I like to use one of the button libraries.