Can't create a loop in case

Hello to everyone,
I'm trying to make a meditation lamp with the nightlight mod. I'm currently using ardunio uno, touch sensor and a neopixel ring.
Case 1 is meditation mode and the function in this case only work once and stop. I want to loop it. I tried things like goto while if but no results.
Thanks for helps.

#include <Adafruit_NeoPixel.h>
#define CLOSED LOW
#define numberOfPixels 16
Adafruit_NeoPixel ringlight = Adafruit_NeoPixel(numberOfPixels, 7, NEO_RGB + NEO_KHZ800);
int flag = 0;
char incDec = 1;
char pixelNumer = 0;

const byte buttonPin = 2;
const byte maximumState = 3;
byte buttonState = 0;
byte lastButtonState = 0;
byte mState = 0;

unsigned long commonMillis;
unsigned long switchMillis;

void setup() {
  Serial.begin(9600);
  ringlight.begin();
  ringlight.show();
  ringlight.setBrightness(50);
  pinMode(buttonPin, INPUT_PULLUP);
}

void medit() {
  if (flag == 1 && millis() - commonMillis >= 250) {
    commonMillis = millis();
    ringlight.setPixelColor(pixelNumer, 0, 0, 100);
    ringlight.show();
    pixelNumer++;
    if (pixelNumer > numberOfPixels - 1) {
      pixelNumer = 0;
      flag = 2;
    }
  }

  if (flag == 2 && millis() - commonMillis >= 7000) {
    commonMillis = millis();
    flag = 3;
  }

  if (flag == 3 && millis() - commonMillis >= 500) {
    commonMillis = millis();
    ringlight.setPixelColor(pixelNumer, 0, 0, 0);
    ringlight.show();
    pixelNumer++;
    if (pixelNumer == numberOfPixels) {
      flag = 1;
      commonMillis = millis();
    }
  }
}

void loop() {
  if (millis() - switchMillis >= 0) {
    switchMillis = millis();
    checkSwitches();
  }
  switch (mState) {
    case 0:
      clearLEDs();
      break;


    case 1:

      medit();


      break;

    case 2:
      if (flag == 1 && millis() - commonMillis >= 40) {
        commonMillis = millis();
        ringlight.setPixelColor(pixelNumer, 255, 145, 10);
        ringlight.show();
        pixelNumer++;
        if (pixelNumer > numberOfPixels - 1) {
          flag = 0;
        }
      }
      break;
  }
}

void checkSwitches() {
  buttonState = digitalRead(buttonPin);
  if (lastButtonState != buttonState) {
    lastButtonState = buttonState;
    if (buttonState == CLOSED) {
      clearLEDs();
      mState++;
      if (mState > maximumState) {
        mState = 1;
      }
      pixelNumer = 0;
      flag = 1;
      commonMillis = millis();
    }
  }
}
void clearLEDs() {

  for (byte x = 0; x < numberOfPixels; x++) {
    ringlight.setPixelColor(x, 0, 0, 0);
  }

  ringlight.show();
}

you might need to reset pixelNumer

1 Like

You just saved my mental health! Thank you very much. It works!!

Have fun

1 Like

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