measurement of time between presses

I made a code that measures the time between presses. But when i run it and monitor using the serial port, the time continously showing on the screen and it looks like it does not measure the time between presses. The code is shown below.

const int switchPin = 2; // the number of the input pin
long startTime; // the value returned from millis when the switch is pressed
long stopTime;
long duration; // variable to store the duration
int flag;
void setup()
{
pinMode(switchPin, INPUT);
digitalWrite(switchPin, HIGH); // turn on pull-up resistor
Serial.begin(9600);
}
void loop()
{
  
if(digitalRead(switchPin) == LOW)
{
startTime = millis();
flag=1;
}
  if(digitalRead(switchPin) == LOW && flag==1)
  flag=0;
{
stopTime = millis();
duration=stopTime-startTime;
Serial.println(duration);
}
}

As long as the switch is held down, extremely rapidly after flag is set to 1, it is set to zero again.

Try this

const int switchPin = 2; // the number of the input pin
unsigned long startTime = 0; // the value returned from millis when the switch is pressed
unsigned long stopTime;
unsigned long duration; // variable to store the duration
unsigned long valueTime = 0;
int currentValue = HIGH;
int previousValue = HIGH;
void setup()
{
  pinMode(switchPin, INPUT);
  digitalWrite(switchPin, HIGH); // turn on pull-up resistor
  Serial.begin(9600);
}
void loop()
{
  currentValue = digitalRead(switchPin);
  if (currentValue != previousValue && millis() - valueTime > 20) // 20 ms debounce time
  {
    valueTime = millis();
    if (currentValue == LOW) //pressed !
    {
      stopTime = millis();
      duration=stopTime - startTime;
      Serial.println(duration);
      startTime = stopTime;
    }
    previousValue = currentValue;
  }
}

You could use Mr. Gammon's SwitchMonitor and return interval.

See the end of reply #1
Or use this:
http://gammon.com.au/Arduino/SwitchManager.zip

.

For the code in the Original Post I think the { on line 24 should actually be between lines 22 and 23.

...R

Thanks @ Mr. bricoleau