 # How did changing the order of this code fix my problem?

Hi everyone,

This question isn’t about code that has broken, but code that I managed to fix today, but I really don’t know why it works! -

My project is an early prototype of a clock that will eventually use Adafruit Neopixels to communicate the time. I have built a series of timers programmed into the code that print to the Serial Monitor. One of the timers (in the code it’s called DialPos) is supposed to count in seconds and will eventually light the neopixels more brightly in sequence.

Here is my code - I have commented the error I made (in referencing DialPos after the first block of integer equations) and the fix I made (actually putting DialPos after the for loop that calculates the equation).

When DialPos was in the first position (now commented out), it was returning ‘11’. Now, it counts up from 0, and resets at 11. My question is: Why has this change of the code structure fixed my problem?

``````// establish integers
long time;

int  Tsecs;
int DialPos;
int realsecs;
float secs;

int  Rsecs;
int  Gsecs;
int  Bsecs;

void setup() {
Serial.begin(9600);
}

void loop() {

float Step = 1.5; //Step is the brightness increment for the non-colour time indication
time = millis();
realsecs = time / 10;

Rsecs = (realsecs + 4500) % 6000;
Gsecs = (realsecs + 500 ) % 6000;
Bsecs = (realsecs + 2500) % 6000;
Tsecs = (realsecs) % 6000;
// DialPos = (Tsecs / 500); // position that didnt work - started at 11 and didn't change.

float DialPosArray;

for (int j = 0; j < 12; j++) {

if (DialPos = j) {
DialPosArray[j] = Step;
}

else {
DialPosArray[j] = 1;

}
}

DialPos = (Tsecs / 500); // new position that does work - counts from 0, resets at 11

Serial.print(millis()); Serial.print("  ") ;
Serial.print(Tsecs); Serial.print("   ") ;
Serial.println(DialPos); Serial.print("  ") ;

}
``````

A

`````` if (DialPos = j)
``````

OOps

Eeeh? Sorry, I don't know what's wrong with it! The code works as I hope it would with that line in it?

That bit is for when I am cycling through my neopixels, and I'd like them to be a bit brighter in a sequence, so it cycles through my (between 1-12) neopixels and the idea is that they'll brighten. When I've gotten around to that bit :)

= is not ==

The line quoted is not comparing them as you intend. It is assigning the value of j to DialPos. That's why rearranging your code looks like it fixed the problem.

The logical outcome of that works out to be "true" which also means you're always setting DialPosArray[j] = Step. So your code will eventually fail again once you expand it to use the array values somewhere.

I see now! Thanks so much for explaining this!