Loading...
Pages: [1]   Go Down
Author Topic: Single instance button press  (Read 210 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 18
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hello, a part of my code has a loop where I add 5 to a value for every button press (0->5->10->etc.). It works, but whenever I press the button for about a second, the value increases by hundreds. It seems like the button goes high, low, high, low, etc. very quickly until i let go of the button. Is there a way to limit the state change to just 1 per press? For example, a 1 second press would only add 5. same as a 12 sec press, it would add only 5 to the value.

Code:

int holding=3
int value=0;
while (holding==3){

GLCD.CursorToXY(70, 45);
GLCD.print(value);
val1=digitalRead(button1);
if (val1==LOW){value=value+5;}

}
Logged

Boston
Offline Offline
God Member
*****
Karma: 3
Posts: 520
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I would add a counter.  Something like this (untested).
Code:
int value=0;
int button1=5;
int x=0;
void setup()
{                 
}

void loop()
{
  int val1=digitalRead(button1);
  if (val1==LOW)
  x++;

  if (x == 1)
  (value=value+5);

if (val1==HIGH)
  x=0;
}
}
Logged

California
Offline Offline
Edison Member
*
Karma: 37
Posts: 1828
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Test for a signal edge rather than the button's state. Look at the StateChangeDetection example.
Logged

UK
Offline Offline
Tesla Member
***
Karma: 89
Posts: 6313
-
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

It seems like the button goes high, low, high, low, etc. very quickly until i let go of the button. Is there a way to limit the state change to just 1 per press?

You aren't detecting the button going high/low - you're detecting whether it is low. This will trigger again and again as fast as your loop() runs, while the button remains pressed. Follow Arrch's example to see how to detect transitions between pressed/unpressed, which is what you need here.
Logged

Pages: [1]   Go Up
Print
 
Jump to: