Arduino leds lighting without pressing the button

-1

I do not know the reason, but the LEDs light up even if I do not push the button.

    int button = 12;
    int led1 = 2;
    int led2  = 3;
    int led3  = 4;
    int led4 = 5;
    int led5 = 6;
    int led6 = 7;

    int buttonState = 0;
    long randNumber; 

    void setup(){
      pinMode(led1, OUTPUT);
      pinMode(led2, OUTPUT);
      pinMode(led3, OUTPUT);
      pinMode(led4, OUTPUT);
      pinMode(led5, OUTPUT);
      pinMode(led6, OUTPUT);

      pinMode(button, INPUT);
      Serial.begin(9600);
      randomSeed(analogRead(0));
    }

     void loop(){
      if (digitalRead(button) == HIGH){
            buttonState = 1;
            randNumber = random(1, 7);
            delay(100);
            Serial.println(randNumber);

            if (randNumber == 6){
              seis();
            }
            if (randNumber == 5){
              cinco();
            }
            if (randNumber == 4){
              quatro();
            }
            if (randNumber == 3){
              tres();
            }
            if (randNumber == 2){
              dois();
            }
            if (randNumber == 1){
              um();
            }
              delay(5000);
              zero();
              buttonState = 0;
          }
      else{
          zero();
          buttonState = 0;
      }
     }
     void seis()
    {
      digitalWrite(led1, HIGH);
      digitalWrite(led2, HIGH);
      digitalWrite(led3, HIGH);
      digitalWrite(led4, HIGH);
      digitalWrite(led5, HIGH);
      digitalWrite(led6, HIGH);
    }

    void cinco()
    {
      digitalWrite(led1, HIGH);
      digitalWrite(led2, HIGH);
      digitalWrite(led3, HIGH);
      digitalWrite(led4, HIGH);
      digitalWrite(led5, HIGH);
    }

    void quatro()
    {
      digitalWrite(led1, HIGH);
      digitalWrite(led2, HIGH);
      digitalWrite(led3, HIGH);
      digitalWrite(led4, HIGH);
    }

    void tres()
    {
      digitalWrite(led1, HIGH);
      digitalWrite(led2, HIGH);
      digitalWrite(led3, HIGH);
    }

    void dois()
    {
      digitalWrite(led1, HIGH);
      digitalWrite(led2, HIGH);
    }

    void um(){
      digitalWrite(led1, HIGH);
    }

    void zero(){
      digitalWrite(led1, LOW);
      digitalWrite(led2, LOW);
      digitalWrite(led3, LOW);
      digitalWrite(led4, LOW);
      digitalWrite(led5, LOW);
      digitalWrite(led6, LOW);
    }
    
asked by anonymous 30.05.2018 / 21:05

1 answer

2

@freddoggo, the line below

if(digitalRead(button) == HIGH)

It has to be

if(digitalRead(button) == LOW)

As any oscillation in the input current ends up generating a false positive for the Arduino processor.

So, a good practice is to keep the door always on and the button lands on the door, so you always read the LOW.

Search for internal arduino pull-up resistor (below)

pinMode(button, INPUT_PULLUP);

A good reference article is: link

    
30.05.2018 / 21:53