Reputation: 49
I'm making a really simple project in Arduino and it's all working fine besides the button which reads the click as a hold, and I want it to be read as a single click.
I have a digital display connected to my Arduino and it's supposed to show the number 5 and once I click on the button the number should increment by 5, but when I click it keeps adding 5 until I let go, so a single click goes from 5 to 155 instead of 10.
buttonState = digitalRead (btnPin);
if (buttonState == LOW)
{
leilao = leilao + 5;
sevseg.setNumber(leilao);
sevseg.refreshDisplay();
previousMillis = currentMillis;
}
"leilao" is the value that should get increased by 5.
Upvotes: 2
Views: 14275
Reputation: 345
Assumptions:
A button click can be defined as a button press followed by a button release. A button press or a button release may be detected in the pin by reading the pin using digitalRead(2). If the value read were LOW then the button has been pressed. If the value read were HIGH then the button has been released. Thus if the values of two consecutive reads are LOW and HIGH then a button click has occurred. A Petri Net Model of Button Clicks includes a simulation and an example sketch for the system you described.
Upvotes: 0
Reputation: 483
You need to get the "edge" of the signal. Try this:
#define btnPin 2
uint8_t btn_prev;
void setup() {
pinMode(btnPin, INPUT_PULLUP);
btn_prev = digitalRead(btnPin);
}
void loop() {
uint8_t btn = digitalRead(btnPin);
if (btn == LOW && btn_prev == HIGH)
{
//your code here
}
btn_prev = digitalRead(btnPin);
}
You can think of a buttons signal as a square. When the button is not pressed there is nothing, when you press it, the voltage flows, so it looks like this:
So your original code was changing the value for the entire "on" duration. The code above, looks for the "rising edge" in the diagram, which is theoretically a single moment in time.
If this doesn't work for you, then look at the "Debouncing" tutorial from Arduino where it also adds in the concept of time until your code is triggered here.
Upvotes: 10