0

This is a pseudo code from my LED cube project

void loop(){
  //switch( map(constrain(analogRead(pt),10,1020),10,1020,1,4));  - for select pattern
  //show(1);
 for(lp=128;lp>=1;lp = lp/2){
  runfor(1000,lp,1,0,0,0,0);
  //Serial.println("HI");
 }
}

void runfor(short mills,byte a,byte b,byte c,byte d,byte e,byte f){
  timer = millis();
  Serial.println(a);
  while((millis()-timer)<=mills){
    light_L1(a,b);
    //light_L2(c,d);
    //light_L3(e,f);
  }
}

the variable 'lp' here never changes its value and remains 128

Why is this?

7
  • 1
    What makes you believe lp does not change? Aug 26, 2018 at 10:18
  • Tested using serial.println, second line in the runfor()
    – A.Shetye
    Aug 26, 2018 at 10:53
  • 1
    I run it. no surprise. the value changes as expected.
    – Juraj
    Aug 26, 2018 at 11:26
  • @Juraj Is this a problem with my chip or IDE then?
    – A.Shetye
    Aug 26, 2018 at 11:30
  • 3
    no. it is a problem of your snippet. it makes something else like the sketch from which you extracted it and didn't test
    – Juraj
    Aug 26, 2018 at 11:32

2 Answers 2

1

Don't ever use a global variable for for loop.

You use the same variable in functions for loops which count down to zero. If lp is zero for loop in loop() ends and new loop() starts.

2

When I ran your code as you presented it in the chat, lp stayed at 128. When I commented-out the "light_L1()" call in "runfor()", lp decremented by 1/2 its value per step as you would expect. The issue is that lp is global and therefore, accessible by any other function. One of your lower functions is resetting it.

2
  • so I induced the asker to post the code and the problem showed itself. but you didn't explain why the value jumps to 128
    – Juraj
    Aug 26, 2018 at 15:06
  • The value changes because one of the lower functions changes it. Why didn't I continue to debug it down to the last detail? 1) To not steal a potential learning experience from the OP; and 2) because it really doesn't matter to the question: "the variable 'lp' here never changes its value and remains 128 Why is this?". I pointed the overall problem - modification of a global from multiple places in the code. The rest is up the OP, who can ask for further help if s/he wants it.
    – JRobert
    Aug 26, 2018 at 15:17

Not the answer you're looking for? Browse other questions tagged or ask your own question.