I'm new to Arduino programming (actually I'm good at software programming but not an expert.) the code of Arduino isn't working as I expect.
I'm working on the debouncing code. the idea is I have 6 LEDs (from pin 2 to 8) attached on the breadboard and incorporated a counter that counts how many time a push button is pressed and those numbers of LEDs are turned on.
ie: If I press pushbutton 4 times then 4 LEDs should on and other remain off.
But as I upload program, All LEDs remain turned on. 2 numbers are added instead of one to counter everytime I press the button.
Here is the code. Please Let me know what I'm doing wrong.
//////////////////////Declarations//////////////////
boolean lastButton = LOW;
boolean currentButton = LOW;
int counter = 2;
int pushbutton = 2;
///////////////////////////setup///////////////////
void setup() {
// put your setup code here, to run once:
pinMode (pushbutton, INPUT);
for (int i=3;i<=8;i++){
pinMode (i, OUTPUT);
}
Serial.begin (9600);
}
///////////////Debouncing/////////////////
boolean debounce (boolean last) {
boolean current = digitalRead (pushbutton);
if (last != current) {
delay (130);
}
return current;
}
//////////////////////LOOP///////////////////////
void loop() {
// put your main code here, to run repeatedly:
currentButton = debounce (lastButton);
if (currentButton != lastButton) {
counter ++;
Serial.print (counter);
Serial.print (" ");
}
for (int i=3; i<=8;i++){
digitalWrite (i,HIGH);
}
if (counter == 9){
counter = 3;
}
delay (100);
lastButton = currentButton;
}
If you are not reading switches correctly, it is almost always a wiring issue. INPUT expects you to be using a switch AND a pullup or pulldown resistor, which requires more complicated wiring than INPUT_PULLUP.
If you want to avoid bounce then you should wait a short interval (such as 50 millisecs) before you read the I/O pin to allow time for the mechanical switch state to settle.
If you only want to respond to the switch if it has been released after the last input then you need to compare the current value with the last value and only return a switch-pressed indication if the current is different from the previous and if the current value shows that the switch has been pressed. For example
if (newValue != prevValue and newValue == LOW) { // assumes LOW when pressed
switchPressed = true;
}
else {
switchPressed = false;
}
prevValue = newValue;
return switchPressed;