I'm going around in circles trying to understand why a variable changes unexpectedly.
I have some code that sends data to a remote wi-fi Arduino device. Its copied form other projects online.
I am busy changing it ready to use to for DMX.
I have added loads of serial prints so I can try to understand why the variable changes.
If you look at the serial output, the value of opMode is 7 in setup routine.
Then before the If its still 7.
Then inside the else, its suddenly 0.
I just cannot understand why it changes and what i am doing wrong.
Thanks in advance for advice and suggestions, even if its pointing out I'm being stupid
The point of having op_Mode is that this will be the value sent to the remote device.
the old_opMode value is so that I can check if this value has already been sent on the previous loop and not send it again. The original code would keep re-sending the same value which just causes unnecessary traffic.
I've made the changes and was very hopeful, however I am still getting issues.
old_opMode is somewhere being reset to zero.
It runs through loop once, correctly. Then it runs the routine the first time (case 7), then it sets old_opMode = opMode. Sends this to the serial port so I know its correct.
Then the loop runs again, and somehow old_opMode is back at zero...
This “variable” old_opMode is ALWAYS 0 (it’s a const):
const int old_opMode = 0;
This redefinition of the scope of the same variable name is a real variable:
int old_opMode = opMode;
However, note that because you have redeclared it (by proceeding with the type name “int”) it is a completely different copy of the variable with its own storage.
It’s “scope” (where it is seen and used from) exists only within the code block (inside the { }) where it is defined. Outside that any reference to “old_opMode” accesses the global const version (always 0).
If you want to change the global old_opMode remove the “int” and “const“ from the above code snippets.
Never ever declare global and local variables with the same names. C allows it and understands it, but from a humans point of View it results in a huge amount of potential misunderstanding.