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