Turn LED on when more than one button pressed

I’m currently trying to figure out, how i can turn on an led if one button or more (4 total) are pressed.
My idea was to connect the buttons to digital pins 2-5. when a button is pressed there will be a positive voltage at pin 1-5. next i wanted to digital read all pins, when they are high they equal 1. then i wanted to sum them and turn the Led on if the sum is > 1…
Unfortunately my current code does not work :((


LEDthingy.ino (1.06 KB)

Unfortunately my current code does not work :((

The code is not what you want:
You mix up two actions

  1. assigning a "value" to a "variable". This is done like that:
    int state; // declare a variable (only once in the program)
    state=1; // assigne a value to the variable (can happen many times)

  2. writing to an OUTPUT PIN, so it becmes HIGH or LOW. This is done like that:
    digitalWrite(pinNumber, HIGH);

So this is not correct:

  st1 = digitalRead(s1);
  if (s1 == HIGH) {
    digitalWrite(st1, 1);
  else {
    digitalWrite(st1, 0);

s1 is holding a pin-number and st1 is a variable that shall become assigned a value.

Most likely you just want that:

  st1 = digitalRead(s1);  // now st1 is either 1 (HIGH) or 0 (LOW)

HIGH and LOW are just other names for the numbers 1 and 0.

And further down in your sketch you do not want that:

 if (st1 + st2 + st3 + st4 > 1) {
    digitalWrite(sum, 1);
  else {
    digitalWrite(sum, 0);

but you want that:

  sum= st1 + st2 + st3 + st4;

Please make changes, then try again!

Then post your code again, I can tell you some other things about.

i will try it out now. thanks :smiley:

LEDthingy.ino (787 Bytes)

it worksss!!!

it worksss!!!!!!


So let me just say a word about 'failsafe programming':

You can avoid a lot of mistakes if you would give your variables meaningful names.

Such if you declare pin numbers, name the variable something with "pin" in its name, such like:

const int pin_s1 = 2;
const int pin_s2 = 3;
const int pin_s3 = 4;
const int pin_s4 = 5;
const int pin_LED =13;

And name your "state" variables something with "state" in its name, such like:

int state1 = 0;
int state2 = 0;
int state3 = 0;
int state4 = 0;

So later in your code you could easily detect mistakes if you ever should try to read other than a pin such like (wrong):

  state1 = digitalRead(state1);

instead of (correct):

  state1 = digitalRead(pin_s1);

as you might remember that digitalRead() expects a pin number as the parameter.