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);
}
}