Increment operator does not work properly

Hi everyone, I am working on a project of making switch case and circling it every several time passed. I am using FastLed library too so in my code I am using EVERY_N_MILLISECONDS.

In my coding below, why is the int set doesn't increment properly. My intention was to rotating the case from 0 to 3 by adding 1 every N seconds.
By monitoring from serial monitor the set number can jump into hundreds resulting the case was broken.

unsigned int x = 0;
unsigned int y = 0;
unsigned char set=0;

void setup() {
  FastLED.addLeds<LED_TYPE, LED_PIN_1, COLOR_ORDER>(leds_1, NUM_LEDS_1).setCorrection( TypicalLEDStrip );
  FastLED.addLeds<LED_TYPE, LED_PIN_2, COLOR_ORDER>(leds_2, NUM_LEDS_2).setCorrection( TypicalLEDStrip );
  FastLED.setBrightness(  BRIGHTNESS );
  fill_solid(leds_2, NUM_LEDS_2, CHSV(ghue2,255,255));
  fill_solid(leds_1, NUM_LEDS_1, CHSV(ghue,255,255));
  FastLED.show();
  delay(3000);

  Serial.begin(4800);

void loop()
{
  unsigned long currentmillis2=millis();
  if (currentmillis2-prevmillis2>=10000){
    prevmillis2=currentmillis2;
    fill_solid(leds_2, NUM_LEDS_2, CHSV(ghue2+=ghuedelta,255,255));
  }
       EVERY_N_MILLISECONDS(20000){
      set+=1;
      if(set>3){
        set=0;
      }
    }

  if (current_mA > 400) {
    unsigned int speed = map(current_mA,400,2000,1,100);
    switch(set){
      case 0:
        Running_LED(speed);
        break;
      case 1:
        Progressing_LED(speed);
        break;
      case 2:
        Cumulation_LED(speed);
        break;
      case 3:
        Rainbow_LED(speed);
        break;
     }
     FastLED.show();
     Serial.println(set);
  }

The odd part is, if I put this particular part

unsigned long currentmillis2=millis();
  if (currentmillis2-prevmillis2>=10000){
    prevmillis2=currentmillis2;
    fill_solid(leds_2, NUM_LEDS_2, CHSV(ghue2+=ghuedelta,255,255));
  }
       EVERY_N_MILLISECONDS(20000){
      set+=1;
      if(set>3){
        set=0;
      }
    }

after the switch case under first if statement, it just doing fine, but another problem arise regarding the LED (leds_2[0] colour affected by leds_1) and it is pretty much another long shot case.

Welcome to the forum

Your sketch does not compile, giving multiple errors caused by FastLED.h not being #included and the setup() function having no closing brace, etc

Please show whole code, with all subroutines.

Sorry i didnt post whole code, so I edited most lines and I accidentally delete the closing brace. But the code is working. Just the switch case is the problem.

I stuck at the case because of the set number
Here is my whole code

#include <FastLED.h>
#include <Adafruit_INA219.h>

Adafruit_INA219 ina219;

#define LED_PIN_1     5
#define NUM_LEDS_1    27
#define LED_PIN_2     8
#define NUM_LEDS_2    6
#define BRIGHTNESS    40
#define LED_TYPE      WS2812
#define COLOR_ORDER   GRB
CRGB leds_1[NUM_LEDS_1];
CRGB leds_2[NUM_LEDS_2];

// This example shows several ways to set up and use 'palettes' of colors
// with FastLED.
//
// These compact palettes provide an easy way to re-colorize your
// animation on the fly, quickly, easily, and with low overhead.
//
// USING palettes is MUCH simpler in practice than in theory, so first just
// run this sketch, and watch the pretty lights as you then read through
// the code.  Although this sketch has eight (or more) different color schemes,
// the entire sketch compiles down to about 6.5K on AVR.
//
// FastLED provides a few pre-configured color palettes, and makes it
// extremely easy to make up your own color schemes with palettes.
//
// Some notes on the more abstract 'theory and practice' of
// FastLED compact palettes are at the bottom of this file.

long count = 0;
float ampvalue = 0;

uint8_t ghue=128;
uint8_t ghue2=128;
uint8_t ghuedelta = 15;

static float switchstate = 0;

unsigned long prevmillis=0;
unsigned long prevmillis1=0;
unsigned long prevmillis2=0;

unsigned int x = 0;
unsigned int y = 0;
unsigned char set=0;

void setup() {
  FastLED.addLeds<LED_TYPE, LED_PIN_1, COLOR_ORDER>(leds_1, NUM_LEDS_1).setCorrection( TypicalLEDStrip );
  FastLED.addLeds<LED_TYPE, LED_PIN_2, COLOR_ORDER>(leds_2, NUM_LEDS_2).setCorrection( TypicalLEDStrip );
  FastLED.setBrightness(  BRIGHTNESS );
  fill_solid(leds_2, NUM_LEDS_2, CHSV(ghue2,255,255));
  fill_solid(leds_1, NUM_LEDS_1, CHSV(ghue,255,255));
  FastLED.show();
  delay(3000);

  Serial.begin(4800);

  while (!Serial) {
    // will pause Zero, Leonardo, etc until serial console opens
    delay(1);
  }

  uint32_t currentFrequency;

  Serial.println("Hello!");

  // Initialize the INA219.
  // By default the initialization will use the largest range (32V, 2A).  However
  // you can call a setCalibration function to change this range (see comments).
  if (! ina219.begin()) {
    Serial.println("Failed to find INA219 chip");
    while (1) {
      delay(10);
    }
  }
  // To use a slightly lower 32V, 1A range (higher precision on amps):
  //ina219.setCalibration_32V_1A();
  // Or to use a lower 16V, 400mA range (higher precision on volts and amps):
  //ina219.setCalibration_16V_400mA();

  Serial.println("Measuring voltage and current with INA219 ...");
}


void loop()
{
  float shuntvoltage = 0;
  float busvoltage = 0;
  float current_mA = 0;
  float loadvoltage = 0;
  float power_mW = 0;

  current_mA = ina219.getCurrent_mA();
  
  //switchstate=analogRead(A0);
  //ampvalue=current_mA;
  ampvalue = abs(map(current_mA, 0, 2000, 0, 100));  

  unsigned long currentmillis2=millis();
  if (currentmillis2-prevmillis2>=10000){
    prevmillis2=currentmillis2;
    fill_solid(leds_2, NUM_LEDS_2, CHSV(ghue2+=ghuedelta,255,255));
  }
       EVERY_N_MILLISECONDS(20000){
      set+=1;
      if(set>3){
        set=0;
      }
    }

  if (current_mA > 400) {
    unsigned int speed = map(current_mA,400,2000,1,100);
    switch(set){
      case 0:
        Running_LED(speed);
        break;
      case 1:
        Progressing_LED(speed);
        break;
      case 2:
        Cumulation_LED(speed);
        break;
      case 3:
        Rainbow_LED(speed);
        break;
     }
     FastLED.show();
     Serial.println(set);
  }
  
  else if (current_mA> 100) {
    while ((current_mA > 100) && (current_mA < 400)) {
      for (int i = 0; i < 255; i++) {
        //leds[i]=CRGB::Aqua;
        fill_solid( leds_1, NUM_LEDS_1, CHSV(128, 255, i));
        FastLED.show();
        delay(500 / 255);
      }
      for (int i = 255; i > 0; i--) {
        //leds[i]=CRGB::Aqua;
        fill_solid( leds_1, NUM_LEDS_1, CHSV(128, 255, i));
        FastLED.show();
        delay(500 / 255);
      }
      //unsigned long currentmillis=millis();
      //if (currentmillis-prevmillis>=10000){
      //  prevmillis=currentmillis;
      //  fill_solid(leds_2, NUM_LEDS_2, CHSV(ghue2+=ghuedelta,255,255));
      //}
      //count=count-10;
      //Serial.print("switchstate:     ");Serial.println(switchstate);
      //Serial.println("Idle State");
      //Serial.print("Current:         "); Serial.print(current_mA); Serial.println(" mA");
      //Serial.print("Value:           "); Serial.println(ampvalue);
      current_mA = ina219.getCurrent_mA();
      //switchstate=analogRead(A0);
      //ampvalue = current_mA;
      ampvalue = abs(map(current_mA, 0, 2000, 0, 100));
    }
  }
  
  else {
    for (int i = 0; i < NUM_LEDS_1; i++) {
      leds_1[i] = CRGB::CRGB::Black;
      FastLED.show();
    }
  }
  //Serial.print("switchstate:     ");Serial.println(switchstate);
  //Serial.print("Current:         "); Serial.print(current_mA); Serial.println(" mA");
  //Serial.print("Value:           "); Serial.println(ampvalue);
  //Serial.print("Load Voltage:  "); Serial.print(loadvoltage); Serial.println(" V");
}

void Running_LED(unsigned int &speed){

  leds_1[x] = CHSV(ghue, 255, 255);
  
  for (int i = 0; i <= NUM_LEDS_1; i++) {
      leds_1[i].fadeToBlackBy(100);
  }

  unsigned long currentMillis = millis(); 
  int interval = speed;
  if(currentMillis - prevmillis > interval) {
        prevmillis=currentMillis;
        x++;        
        if (x>NUM_LEDS_1){
            fill_solid(leds_1,NUM_LEDS_1,CRGB::Black);
            x=0;
            ghue += ghuedelta;
        }
    }
}

void Progressing_LED(unsigned int &speed){
    for (int i = 0; i <= x; i++) {
      leds_1[i] = CHSV(ghue, 255, 255);
    }
    unsigned long currentMillis = millis(); 
    int interval = speed;
    if(currentMillis - prevmillis > interval) {
        prevmillis=currentMillis;
        x++;
        //fill_solid(leds,x,CHSV(ghue, 255, 255));
        if (x>NUM_LEDS_1){
            fill_solid(leds_1,NUM_LEDS_1,CRGB::Black);
            x=0;
            y+=1;
            if (y>1){
                ghue += ghuedelta;
                y=0;
            }
        }
    }
}

void Cumulation_LED(unsigned int &speed){  
  leds_1[x] = CHSV(ghue, 255, 255);
  
  for (int i = 0; i <= NUM_LEDS_1; i++) {
      leds_1[i].fadeToBlackBy(100);
  }
  
  unsigned long currentMillis = millis(); 
  int interval = speed/3;
  if(currentMillis - prevmillis > interval) {
    prevmillis=currentMillis;
    x++;
    if (x>NUM_LEDS_1-y){
      y+=2;
      x=0;
    } 
  }
  if (y<NUM_LEDS_1){
     for (int j=0;j<y;j++){
         leds_1[NUM_LEDS_1-y+j]= CHSV(ghue,255,255);
     }
  }else{
        ghue+=(255/4);
        y=0;
   }
}

void Rainbow_LED(unsigned int &speed){
    for (int i = 0; i < NUM_LEDS_1; ++i) {
        leds_1[i] = CHSV(ghue - (i * 255/NUM_LEDS_1), 255, 255);
    }

  //You can change the pattern speed here
    unsigned long currentMillis = millis(); 
    int interval = 10;
    if(currentMillis - prevmillis > interval) {
        prevmillis=currentMillis;
        ghue+=(speed/10);
    }
}

Thank you

This code will go beyond the array boundary and mess up neighboring variables. There are several such places in your program.

As soon as I read that you get different errors depending on the position of the statements in the code - I immediately thought about incorrect memory handling.

1 Like

Yes, another example here:

  leds_1[x] = CHSV(ghue, 255, 255);
  ...
        x++;        
        if (x>NUM_LEDS_1){ // should be x>=NUM_LEDS_1
            ...
            x=0;

So basically the for loop that made the mess or the variables. I am afraid I don't understand the root cause of the problem.

An array has a defined number of elements.

If you over write the size of the array, you destroy other variables.

The for loop has nothing to do with it.
You forgot the fact that arrays in C beginning from zero and it last element is a[Size-1], not the a[Size] !
So your code

for (int i = 0; i <= NUM_LEDS_1; i++)

go to the non-existan element led_1[NUM_LEDS_1]

1 Like

On the contrary, the for loop has everything to do with it

1 Like

Ah I understand it now. I forgot that it starts from 0. Thank you very much for all the help. I will revised my code and see tomorrow.

The issue from what I posted yesterday is solved now.

Here is my revised code. I hope the code is alright now. I also change the baudrate from 300 to 9600

#include <FastLED.h>
#include <Adafruit_INA219.h>

Adafruit_INA219 ina219;

#define LED_PIN_1     5
#define NUM_LEDS_1    27
#define LED_PIN_2     8
#define NUM_LEDS_2    6
#define BRIGHTNESS    40
#define LED_TYPE      WS2812
#define COLOR_ORDER   GRB
CRGB leds_1[NUM_LEDS_1];
CRGB leds_2[NUM_LEDS_2];

// This example shows several ways to set up and use 'palettes' of colors
// with FastLED.
//
// These compact palettes provide an easy way to re-colorize your
// animation on the fly, quickly, easily, and with low overhead.
//
// USING palettes is MUCH simpler in practice than in theory, so first just
// run this sketch, and watch the pretty lights as you then read through
// the code.  Although this sketch has eight (or more) different color schemes,
// the entire sketch compiles down to about 6.5K on AVR.
//
// FastLED provides a few pre-configured color palettes, and makes it
// extremely easy to make up your own color schemes with palettes.
//
// Some notes on the more abstract 'theory and practice' of
// FastLED compact palettes are at the bottom of this file.

long count = 0;
float ampvalue = 0;

uint8_t ghue=128;
uint8_t ghue2=128;
uint8_t ghuedelta = 15;

static float switchstate = 0;

unsigned long prevmillis=0;
unsigned long prevmillis1=0;
unsigned long prevmillis2=0;

unsigned int x = 0;
unsigned int y = 0;
unsigned char set=0;

void setup() {
  FastLED.addLeds<LED_TYPE, LED_PIN_1, COLOR_ORDER>(leds_1, NUM_LEDS_1).setCorrection( TypicalLEDStrip );
  FastLED.addLeds<LED_TYPE, LED_PIN_2, COLOR_ORDER>(leds_2, NUM_LEDS_2).setCorrection( TypicalLEDStrip );
  FastLED.setBrightness(  BRIGHTNESS );
  fill_solid(leds_2, NUM_LEDS_2, CHSV(ghue2,255,255));
  fill_solid(leds_1, NUM_LEDS_1, CHSV(ghue,255,255));
  FastLED.show();
  delay(3000);

  Serial.begin(9600);

  while (!Serial) {
    // will pause Zero, Leonardo, etc until serial console opens
    delay(1);
  }

  uint32_t currentFrequency;

  Serial.println("Hello!");

  // Initialize the INA219.
  // By default the initialization will use the largest range (32V, 2A).  However
  // you can call a setCalibration function to change this range (see comments).
  if (! ina219.begin()) {
    Serial.println("Failed to find INA219 chip");
    while (1) {
      delay(10);
    }
  }
  // To use a slightly lower 32V, 1A range (higher precision on amps):
  //ina219.setCalibration_32V_1A();
  // Or to use a lower 16V, 400mA range (higher precision on volts and amps):
  //ina219.setCalibration_16V_400mA();

  Serial.println("Measuring voltage and current with INA219 ...");
}


void loop()
{
  float shuntvoltage = 0;
  float busvoltage = 0;
  float current_mA = 0;
  float loadvoltage = 0;
  float power_mW = 0;

  current_mA = ina219.getCurrent_mA();
  
  //switchstate=analogRead(A0);
  //ampvalue=current_mA;
  //ampvalue = abs(map(current_mA, 0, 2000, 0, 100));  

  unsigned long currentmillis2=millis();
  if (currentmillis2-prevmillis2>=10000){
    prevmillis2=currentmillis2;
    fill_solid(leds_2, NUM_LEDS_2, CHSV(ghue2+=ghuedelta,255,255));
  }
       EVERY_N_MILLISECONDS(20000){
      set+=1;
      if(set>3){
        set=0;
      }
    }

  if (current_mA > 400) {
    unsigned int speed = abs(map(current_mA,400,2000,1,200));
    switch(set){
      case 0:
        Running_LED(speed);
        break;
      case 1:
        Progressing_LED(speed);
        break;
      case 2:
        Cumulation_LED(speed);
        break;
      case 3:
        Rainbow_LED(speed);
        break;
     }
     FastLED.show();
     Serial.println(set);
  }
  
  else if (current_mA> 100) {
    while ((current_mA > 100) && (current_mA < 400)) {
      for (int i = 0; i < 255; i++) {
        //leds[i]=CRGB::Aqua;
        fill_solid( leds_1, NUM_LEDS_1, CHSV(128, 255, i));
        FastLED.show();
        delay(500 / 255);
      }
      for (int i = 255; i > 0; i--) {
        //leds[i]=CRGB::Aqua;
        fill_solid( leds_1, NUM_LEDS_1, CHSV(128, 255, i));
        FastLED.show();
        delay(500 / 255);
      }
      //unsigned long currentmillis=millis();
      //if (currentmillis-prevmillis>=10000){
      //  prevmillis=currentmillis;
      //  fill_solid(leds_2, NUM_LEDS_2, CHSV(ghue2+=ghuedelta,255,255));
      //}
      //count=count-10;
      //Serial.print("switchstate:     ");Serial.println(switchstate);
      //Serial.println("Idle State");
      //Serial.print("Current:         "); Serial.print(current_mA); Serial.println(" mA");
      //Serial.print("Value:           "); Serial.println(ampvalue);
      current_mA = ina219.getCurrent_mA();
      //switchstate=analogRead(A0);
      //ampvalue = current_mA;
      //ampvalue = abs(map(current_mA, 0, 2000, 0, 100));
    }
  }
  
  else {
    for (int i = 0; i < NUM_LEDS_1; i++) {
      leds_1[i] = CRGB::CRGB::Black;
      FastLED.show();
    }
  }
  //Serial.print("switchstate:     ");Serial.println(switchstate);
  //Serial.print("Current:         "); Serial.print(current_mA); Serial.println(" mA");
  //Serial.print("Value:           "); Serial.println(ampvalue);
  //Serial.print("Load Voltage:  "); Serial.print(loadvoltage); Serial.println(" V");
}

void Running_LED(unsigned int &speed){

  leds_1[x] = CHSV(ghue, 255, 255);
  
  for (int i = 0; i < NUM_LEDS_1; i++) {
      leds_1[i].fadeToBlackBy(5);
  }

  unsigned long currentMillis = millis(); 
  int interval = speed;
  if(currentMillis - prevmillis > interval) {
        prevmillis=currentMillis;
        x++;        
        if (x>=NUM_LEDS_1){
            fill_solid(leds_1,NUM_LEDS_1,CRGB::Black);
            x=0;
            ghue += ghuedelta;
        }
    }
}

void Progressing_LED(unsigned int &speed){
    for (int i = 0; i < x; i++) {
      leds_1[i] = CHSV(ghue, 255, 255);
    }
    unsigned long currentMillis = millis(); 
    int interval = speed;
    if(currentMillis - prevmillis > interval) {
        prevmillis=currentMillis;
        x++;
        //fill_solid(leds,x,CHSV(ghue, 255, 255));
        if (x>=NUM_LEDS_1){
            fill_solid(leds_1,NUM_LEDS_1,CRGB::Black);
            x=0;
            y+=1;
            if (y>1){
                ghue += ghuedelta;
                y=0;
            }
        }
    }
}

void Cumulation_LED(unsigned int &speed){  
  leds_1[x] = CHSV(ghue, 255, 255);
  
  for (int i = 0; i < NUM_LEDS_1; i++) {
      leds_1[i].fadeToBlackBy(8);
  }
  
  unsigned long currentMillis = millis(); 
  int interval = speed/2;
  if(currentMillis - prevmillis > interval) {
    prevmillis=currentMillis;
    x++;
    if (x>=NUM_LEDS_1-y){
      y+=2;
      x=0;
    } 
  }
  if (y<NUM_LEDS_1){
     for (int j=0;j<y;j++){
         leds_1[NUM_LEDS_1-y+j]= CHSV(ghue,255,255);
     }
  }else{
        ghue+=(255/4);
        y=0;
   }
}

void Rainbow_LED(unsigned int &speed){
    for (int i = 0; i < NUM_LEDS_1; ++i) {
        leds_1[i] = CHSV(ghue - (i * 255/NUM_LEDS_1), 255, 255);
    }

  //You can change the pattern speed here
    unsigned long currentMillis = millis(); 
    int interval = 10;
    if(currentMillis - prevmillis > interval) {
        prevmillis=currentMillis;
        ghue+=(speed/75);
    }
}

On the side note. With baud rate 300, function Running LED also left me with 1 last led off and Progressing LED with 2 last leds off. When I change to 9600, the last problem is function Progressing LED 1 last led always off.
Could you suggest what is wrong with this? I hope the LED Strip would run all the way until the very last number of led.

I know it is solved already, still, you don’t have int set in your code

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