0

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);
6
  • 2
    ledPin4 == HIGH? Guess you mean something else. Aug 18, 2016 at 6:25
  • Also, currentMillis = onTime * 100; makes little sense. What did you actually mean? Aug 18, 2016 at 6:29
  • @EdgarBonet I put it in there so if the LED was HIGH and there button pushed it would end the timer in the while loop Aug 18, 2016 at 6:30
  • @MikaelPatel I set the LED to HIGH and then used an if statement to check if it's HIGH and the button was pressed at the same time. I didn't use there == to assign the HIGH state Aug 18, 2016 at 6:33
  • 1
    Then you mean currentMillis = previousMillis + onTime, but that won't work because you assign currentMillis = millis(); right after. Instead, you can simply break out of the while loop. Aug 18, 2016 at 6:52

1 Answer 1

1

You should use

if (digitalRead(ledPin4) == HIGH && (button_press_9()))

instead of

if (ledPin4 == HIGH && (button_press_9()))
1
  • 2
    Since the pin has been set to HIGH right before, the first part of the test seems useless. You can just do if (button_press_9()). Aug 18, 2016 at 15:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.