Conditions being met but the if statement isn't working

I am trying to elicit a response whenever I click a button 5 times under a certain amount of time. Before I get to that, I need to make sure that the conditions work and I am getting the right time. So I am trying to print out the time whenever the conditions are met.

The two conditions are that n == 5 (n increases by 1 whenever I push the button) and that the time is under 15,000. I know that the first condition is being met because the monitor prints out n whenever I press the button. The second condition should also be met because I have timed it myself.

But even when both of these conditions are met, the If statement is not printing out what I want it to print out. Help please.

int ledPin = 13;

int buttonPin = 2;
int buttonState;
int lastButtonState = 0;

int buzzerPin = 9;
int buzzerState;

int n = 0;


unsigned long previous_time = 0;
const int interval = 15000;

void setup()
{
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  pinMode(buzzerPin, OUTPUT);
}

void loop()
{ 
  unsigned long current_time = millis();
  unsigned long button_time = current_time - previous_time;
    
  buttonState = digitalRead(buttonPin);
  delay(50);

  if (buttonState == HIGH)
  {
    digitalWrite(ledPin, HIGH);
  }
  else
  {
    digitalWrite(ledPin, LOW);
  }

  if (buttonState != lastButtonState)
  {
    if (buttonState == HIGH)
    {
      n = n + 1;
      Serial.println(n);
      if (n >= 5)
      {
        n = 0;
      //  Serial.println(current_time);
      }
      if (n == 1)
      {
        previous_time = millis();
      //  Serial.println(previous_time);
      }
    }
    lastButtonState = buttonState;
  }
  
  if (n == 5 && button_time <= interval)
  {
    Serial.println(current_time);
  }
}

How can n be 5 here if you reset it to zero immediately when it reaches 5 here?

`const int interval = 15000;`

Always use unsigned long for any variables associated with millis() or micros().

the way to find the error is:
to printout all details right before the if-condition

Serial.print( F("n:") );
Serial print (n); 

Serial.print( F("  button_time:") );
Serial.print(button_time);

Serial.print( F("  interval:") );
Serial.print(interval);

Serial.print( F(" n ==5:") );
Serial.print(n ==5);

Serial.print( F("   button_time <= interval") );
Serial.print(button_time <= interval);

of course this will take 5 minutes time to write down the code
compare to how long it took to get an answer posted

best regards Stefan

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.