NeoPixel problem along with weird button toggling

So the aim of my code is to have two NeoPixel rings light up while slowly rising in brightness from 0 to 255 when the button is pressed. So in the code I have, I made a variable called "mode" where it reads the value of mode when the button is pressed. The value of mode will execute a function that determines what the NeoPixels show.

The first problem I have with my current code is that once the NeoPixels light up at maximum brightness, it seems to redo the 0 -> 255 brightness thing again (and it keeps on going).

The second problem is that when I click on the button again after I activate the light mode, it sometimes doesn't respond and doesn't change to the other mode.

#include <Adafruit_NeoPixel.h>

#define LED_PIN_A 5
#define LED_PIN_B 6
#define LED_COUNT 24

Adafruit_NeoPixel stripA(LED_COUNT, LED_PIN_A, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel stripB(LED_COUNT, LED_PIN_B, NEO_GRB + NEO_KHZ800);

// constants won't change. They're used here to set pin numbers:
const int buttonPin = 2;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin

// variables will change:
int buttonState = LOW;         // variable for reading the pushbutton status
int lastButtonState = LOW;

int mode = 0;

void off() {
  stripA.clear();
  stripB.clear();
  
  for(int i = 0; i < LED_COUNT; i++) {
      stripA.setPixelColor(i,0,0,0);
      stripB.setPixelColor(i,0,0,0);
  }
  stripA.show();
  stripB.show();
}

void on() {
   for(int x = 0; x < 256; x++) {
    for(int i = 0; i < LED_COUNT; i++) {
      stripA.setPixelColor(i,x,x,x);
      stripB.setPixelColor(i,x,x,x);
    }
   stripA.show();
   stripB.show();
   delay(15);
   }
}

void setup() {
  Serial.begin(9600);
 
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);

  stripA.begin();
  stripB.begin();
  
  buttonState = digitalRead(buttonPin);
}

void loop() {
  lastButtonState = buttonState;
  buttonState = digitalRead(buttonPin);
  
  stripA.clear();
  stripB.clear();
  
  if (lastButtonState == LOW && buttonState == HIGH) {
    mode = mode + 1;
    if(mode > 1) {
      mode = 0;
    }
    Serial.print(mode);
  } 

  if(mode == 0) {
    off();
  }
  else if(mode == 1) {
    on();
  }
}

Show us a good schematic of your proposed circuit.
Show us a good image of your ‘actual’ wiring.
Give links to components.

Components:

Note that there is an extra blue wire compared to the Fritzing because I soldered a blue wire to the button.

Here is the actual wiring

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