I'm using analog pin 5 on Arduino to detect presses from 6 push-buttons. On the picture top-right button is number 1 and then from right to left they go as 2, 3, 4, 5, 6. Program should print 0 when none of the buttons is pressed and if one of them is presses, it should print its position as I mentioned before. Currently the problem is that if I press say second button, it will (instead only once) sometimes print 2 a couple of times. I guess it is because of the "noise" when button is pressed and that it should be debounced, but I don't know how to debounce analog pin.
My code:
int old_button = 0;
int button;
int pressed_button;
int z;
void setup () {
Serial.begin(9600);
pinMode(A5, INPUT);
}
void loop () {
z = analogRead(5);
if (z > 1021) button = 0;
else if (z > 511 && z < 514) button = 1;
else if (z > 680 && z < 684) button = 2;
else if (z > 766 && z < 770) button = 3;
else if (z > 817 && z < 822) button = 4;
else if (z > 851 && z < 856) button = 5;
else if (z > 875 && z < 880) button = 6;
else button = 0;
if (old_button == button) {
old_button = button;
pressed_button = 0;
}
else {
old_button = button;
pressed_button = button;
}
Serial.println(pressed_button);
}
Circuit (2200 ohm resistors):