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 
asked Aug 2, 2015 at 17:26
2
  • 2
    Research a technique called debouncing. Commented Aug 2, 2015 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? Commented Aug 2, 2015 at 18:59

2 Answers 2

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.

answered Aug 2, 2015 at 20:48
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.

answered Aug 2, 2015 at 19:53

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.