Go Down

Topic: Single instance button press (Read 444 times) previous topic - next topic

haha54321

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: [Select]


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

}

Pauly

I would add a counter.  Something like this (untested).
Code: [Select]

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

Arrch

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

PeterH


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.
I only provide help via the forum - please do not contact me for private consultancy.

Go Up