Code running when not called

I have my Arduino set up with an LED light strip, and I am trying to call a function that I made using a pushbutton on pin 6. The function is running before I press the button

#include <FastLED.h>

#define LED_PIN     7
#define BUTTON_PIN 6
#define NUM_LEDS    500
int buttonState = 0;

CRGB leds[NUM_LEDS];
int brightness = 0;

void setup() {
  pinMode(BUTTON_PIN, INPUT);
  Serial.begin(9600);
  FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);
}

void BasicPattern() 
{
  
     for(int i=0;i<50;i++){
        leds[i].setRGB(255,0,0);
        leds[i].fadeLightBy(brightness);
    } 
  FastLED.clear(); 
    for(int i=50;i<NUM_LEDS;i++){
        leds[i].setRGB(255,255,255);
        leds[i].fadeLightBy(brightness);
    }  
  FastLED.show();
    leds[0-50] = CRGB(255, 0, 0);
    FastLED.show();
    delay(500);  
    leds[1] = CRGB(0, 255, 0);
    FastLED.show();
    delay(500);
    leds[2] = CRGB(0, 0, 255);
    FastLED.show();
    delay(500);
    leds[5] = CRGB(150, 0, 255);
    FastLED.show();
    delay(500);
    leds[9] = CRGB(255, 200, 20);
    FastLED.show();
    delay(500);
    leds[14] = CRGB(85, 60, 180);
    FastLED.show();
    delay(500);
    leds[19] = CRGB(50, 255, 20);
    delay(500);
    FastLED.clear();
      for(int dot = 0; dot < NUM_LEDS; dot++) { 
              leds[dot] = CRGB::Blue;
              leds[dot+1] = CRGB::Blue;
              FastLED.show();
            // clear this led for the next time around the loop
              leds[dot] = CRGB::Black;
              delay(30);
      } 
  }

void loop(){
  buttonState = digitalRead(BUTTON_PIN);
  if (buttonState == HIGH) {
    BasicPattern();
}
}

Most of the function can be ignored, I just want to know why the function is running when not called.

How did you connected the button?
Draw your project freehand and post it here.

Unless you have an external pull up or down resistor the pin is floating and can have arbitrary changing values.

Try..

pinMode(BUTTON_PIN, INPUT_PULLUP);


if (buttonState == LOW) {
   BasicPattern();
   while(digitalRead(BUTTON_PIN)==LOW) delay(10);
}

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.