hello , i need to register the time each button (there are 2 buttons ) has pressed to compare the difference ,
the time of the press of button1 - the time of the pree of button2
or vise versa should be less than 50ms to light up a redled
here what i tried to code but its not working fine , please help!
int button =3;
int button2 =4;
int redled =5;
void setup () {
pinMode(button,INPUT);
pinMode(button2,INPUT);
pinMode(redled,OUTPUT);
}
void loop () {
unsigned long firstpress;
unsigned long secondpress;
if (digitalRead(button)==HIGH) {
firstpress = millis();
}
if (digitalRead(button2)==HIGH) {
secondpress = millis();
}
if (firstpress - secondpress <= 50) {
digitalWrite(redled,HIGH);
delay(2000);
}
firstpress = digitalRead(button);
secondpress = digitalRead(button2);
}
How many times do you suppose loop() will iterate before both switches are pressed? Does creating a new variable on each pass make sense? To me, it does not.
Make the times static or global so that doesn't happen.
No, there's a fundamental problem here - you are not detecting when the button is pressed.
The button is pressed at the point where it now reads HIGH but last time it read LOW - you have
to save the state of the last time you called digitalRead() and compare against the new reading.
Have a look at StateChangeDetection example (I think that's the name) in the Arduino examples.