0

I have realised an electrical circuit that gives 5V in output. When I press a button, it gives 0V. So I have in output a square wave (5V - 0V). I would like to count how many times I press the button, by using an Arduino MEGA AT2560. I have written this code below, but it doesn't work, because when I press the button, it increase the counter three or four times. For example: I press the button 5 times, but the counter has arrived to 30!

#include <SD.h>
#include <SPI.h>

unsigned int count_hall_f = 0;

void setup()
{
  Serial.begin(9600);
  attachInterrupt(0, interrFront, RISING); //18  
}

void loop(){

}

void interrFront() {
  count_hall_f++;
  Serial.println(count_hall_f);
}

An example of the result is:

1 <- I pressed here
2
3 <- I pressed here
4
5
6
7
8
9
10
11
12 <- I pressed here
13
14
15
16 
  • 2
    Research a technique called debouncing. – CharlieHanson Aug 2 '15 at 17:55
  • Yeah, I've used a RC filter and it does work. I have choosen the values of R and C by experiments. Do you have a suggest for choose these values? – Bernheart Aug 2 '15 at 18:59
1

I have choosen the values of R and C by experiments. Do you have a suggest for choose these values?

I have a page about switches - somewhat down the page is a discussion of debouncing, including some calculations which show how you can calculate the debounce time. With the switch pin pulled high by the internal pull-up (something you don't appear to be doing), and a 1 µF capacitor, that gives you a debounce of about 35 ms.


Example schematic:

Hardware debounce

Results on input pin:

Debounce scope image

(Maths supporting that figure on the above page).


Note that it is important to have a pull-up or pull-down for your switch or it will read random values if not closed.

0

Simple way to do it: since the first interrupt, wait a pre-determined amount of time (depends on the button you use, could be 100us to few tens of ms) and check again that the value is what triggered the interrupt.

This will kill the effect of the mechanical bounces.

You can even disable interrupts during the delay.

There are much more sophisticated way to do it, but this should be good enough to get you started on the way to debounce your inputs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.