This is a snip it of code from a program I am writing. I have the program turn an LED on and if a button is pressed when the LED is on I want it to add to a counter and print the counter value. The problem seems that my if statement is skipped. Right now the while loop is setup for 5 seconds using millis() and stays off using a short delay. This part (button_press_9())) is a function call to a Boolean I have setup for debouncing. If I put the function call in an if statement by its self for example to test it. It works and will turn an LED on and off. It seems the combination of the two is incompatible.
Thank you in advance.
unsigned long previousMillis = millis();
unsigned long currentMillis = millis();
while ((currentMillis - previousMillis) < onTime)
{
digitalWrite(ledPin4, HIGH);
if (ledPin4 == HIGH && (button_press_9()))
{
counter++;
Serial.println(counter);
currentMillis = onTime * 100;
}
currentMillis = millis();
}
digitalWrite(ledPin4, LOW);
delay(1000);
1 Answer 1
You should use
if (digitalRead(ledPin4) == HIGH && (button_press_9()))
instead of
if (ledPin4 == HIGH && (button_press_9()))
-
2Since the pin has been set to
HIGH
right before, the first part of the test seems useless. You can just doif (button_press_9())
.Edgar Bonet– Edgar Bonet2016年08月18日 15:58:02 +00:00Commented Aug 18, 2016 at 15:58
currentMillis = onTime * 100;
makes little sense. What did you actually mean?currentMillis = previousMillis + onTime
, but that won't work because you assigncurrentMillis = millis();
right after. Instead, you can simplybreak
out of thewhile
loop.