I want to find the timing between HIGH state and LOW state of push button. For that, I made a program. You can see my program below. In my program, I made logic like that when switch is pressed then one variable "currentMillis" store the value of millis() and it store value until button pressed. But whenever I pressed button again then it also add previous value. For example, if button pressed for first time then suppose we got 200ms, now suppose if button pressed second time then we got 500ms and if button pressed third time then we got 1000ms. That mean every time value added. No doubt I made a logic which seem to be perfect but I can't figure out what is problem. Please give me some suggestions.
const int buttonPin = 2;
unsigned long currentMillis = 0;
unsigned long previousMillis = 0;
unsigned long finalMillis = 0;
int buttonPushCounter = 0;
void setup()
{
Serial.begin(9600);
pinMode(buttonPin, INPUT);
digitalWrite(buttonPin, HIGH);
}
void loop()
{
if (digitalRead(buttonPin) == LOW)
{
buttonPushCounter++;
Serial.println("on");
Serial.print("number of button pushes: ");
Serial.println(buttonPushCounter);
while(digitalRead(buttonPin) == LOW)
{
currentMillis = millis();
}
finalMillis = currentMillis - previousMillis;
Serial.println(finalMillis);
previousMillis = finalMillis;
//finalMillis = 0;
}
}
Here, it is my serial monitor output.
on
number of button pushes: 1
0
on
number of button pushes: 2
775
on
number of button pushes: 3
873
on
number of button pushes: 4
1425
on
number of button pushes: 5
1496
on
number of button pushes: 6
2073
on
number of button pushes: 7
2010
on
number of button pushes: 8
2643
on
number of button pushes: 9
3052
on
number of button pushes: 10
3195
on
number of button pushes: 11
3396
on
number of button pushes: 12
3575
on
number of button pushes: 13
3737