Joao costa
Joao costa

Reputation: 49

How to make button read a single click and not hold in arduino

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

Answers (2)

Assumptions:

  1. One end of the button is connected to pin 2 and the other end of the button is connected to GND of an Arduino Uno microcontroller board.
  2. In the setup pin 2 is initialized as follows: pinMode(2, INPUT_PULLUP);

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

Breno Teodoro
Breno Teodoro

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:

enter image description here

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

Related Questions