Go Down

Topic: Basic button code need a look (Read 26 times) previous topic - next topic

admaltais

Today at 06:08 am Last Edit: Today at 06:16 am by admaltais
Hi Arduino friend,

i'm new in electronics & c++, i'm learning right now and i'm stuck with a really basic setup!!
I have tryied with or without capacitor
I want to light the led as mush as i click to the push button,
0 clic = 0 led
1 clic = 1 led
2 clic = 2 led ...

For now, when i push the plus button, both led turn on, if i press minus, both turn off.
In order:
1 clic plus = 2 led on
2 clic plus = 2 led on
1 clic minus = 2 led on
1 clic minus = 0 led on

Thanks for the help

Code: [Select]

const int led1=13;
const int led2=12;

const int btnPlus=2;
const int btnMinus=3;

int nbLed = 0;

void setup(){
  pinMode (btnPlus, INPUT);
  pinMode (btnMinus, INPUT);
  pinMode (led1, OUTPUT);
  pinMode (led2, OUTPUT);
}


void loop(){
     
     if ( digitalRead(btnPlus) == LOW){  //bouton plus pushed
       nbLed++;
     }
     if (digitalRead(btnMinus) == LOW){  //bouton minus pushed
       nbLed--;
     }
     if (nbLed>=2){
       nbLed = 2;
     }
     if (nbLed<=0){
       nbLed = 0;
     }
     allumage(nbLed);
}

void allumage (int i){
   
    if (i == 0){
      digitalWrite(led1,HIGH);
      digitalWrite(led2,HIGH);
    }
    if (i == 1){
      digitalWrite(led1,LOW);
      digitalWrite(led2,HIGH);
    }
    if (i == 2){
      digitalWrite(led1,LOW);
      digitalWrite(led2,LOW);
    }

}

LarryD

You have to realize there still may be contact bounce with your switches.
Try to add some software debounce to your code.
For debug purposes only adding some delays, try 100ms, at strategic locations to slow things down.

Also this should have been asked in the programming forum.
The way you have it in your schematic isn't the same as how you have it wired up!

admaltais

Hi Larry and thank you,

I've read about software debounce, that is a good way to avoid bouncing. I've found the simple while loop works great!

Code: [Select]
if ( digitalRead(btnPlus) == LOW){  //bouton plus pushed
       while(digitalRead(btnPlus) == LOW);
       nbLed++;
     }


But why we should use a capacitor if it is not the solution to the rebound?
Thanks

Go Up