As the title says, I have a problem with the sketch. ALL i want is to make a program that calculates the time between two pushes of a button. If i press a button and press it again, lets say, 2.341 seconds later, i want the number 2341 to be displayed. Code I made that doesnt work:
const int buttonPin = 12;
unsigned long time1;
unsigned long time2;
int buttonState = 0;
unsigned long interval;
bool x = 0; //control
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
Serial.begin(9600);
}
void loop() {
buttonState = digitalRead(buttonPin);
if (buttonState == LOW && x == 0) { //if button IS pushed
x = 1;
time1 = millis();
while(buttonState == LOW) buttonState = digitalRead(buttonPin);
buttonState = HIGH;
}
if (buttonState == LOW && x == 1) { //if button IS pushed
x = 0;
time2 = millis();
while(buttonState == LOW) buttonState = digitalRead(buttonPin);
buttonState = HIGH;
interval = time2 - time1;
Serial.print("Interval:");
Serial.println(interval);
}
}
x is the control variable that passes the next if to read so there isnt second reading of time1 before time 2; after the second readind the interval should be displayed
PLEASE dont tell me how to correct the code, please you try to fix it and send the working code in the comments. Thanks
Thanks but apart from the real time intervals there are also some strange prints like 0 and 143 when i hold the button for around a second. Actually this whole code is part from a bigger that takes the interval and converts it into RPM using the 60*(1000/interval) formula. Thanks anway but even the code that Iesept provided does not work. For now i just need the interval to be measured.
there are also some strange prints like 0 and 143 when i hold the button for around a second.
switch bounce issues.
I find it convenient to use the Bounce2 library.
#include <Bounce2.h>
Bounce rpmSelectorButton = Bounce();
unsigned long startTime;
unsigned long currentTime;
unsigned long interval;
const byte buttonPin = 12;
boolean timing = false;
void setup()
{
Serial.begin(115200);
pinMode(buttonPin, INPUT_PULLUP);
Serial.println("Interval Timer Demo");
rpmSelectorButton.attach(buttonPin);
rpmSelectorButton.interval(25); // debounce period in ms
}
void loop()
{
currentTime = millis();
rpmSelectorButton.update();//debounced digitalRead()
if(rpmSelectorButton.fell() && ! timing)
{
startTime = currentTime;
timing = true;
Serial.println("start interval timing ");
rpmSelectorButton.update();//ensures new debounce reading for second press
}
if (rpmSelectorButton.fell() && timing)
{
interval = millis() - startTime;
timing = false;
Serial.println("end interval timing");
Serial.print("Time between button presses ");
Serial.println(interval);
}
}
I would think the the interface would be better to time the interval between button press and release. That is, the time the button is held down. Substitute here
//if (rpmSelectorButton.fell() && timing)
if (rpmSelectorButton.rose() && timing)